CREATE TYPE "domain_event_type" AS ENUM('task.finished', 'task.checked', 'task.sent_back', 'task.reminded', 'task.missed');--> statement-breakpoint
CREATE TABLE "domain_events" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
	"type" "domain_event_type" NOT NULL,
	"task_instance_id" uuid,
	"actor_person_id" uuid,
	"payload" jsonb,
	"occurred_at" timestamp with time zone DEFAULT now() NOT NULL,
	"dispatched_at" timestamp with time zone
);
--> statement-breakpoint
CREATE TABLE "notifications" (
	"id" uuid PRIMARY KEY DEFAULT gen_random_uuid(),
	"person_id" uuid NOT NULL,
	"event_id" uuid NOT NULL,
	"message_key" text NOT NULL,
	"task_instance_id" uuid,
	"created_at" timestamp with time zone DEFAULT now() NOT NULL,
	"read_at" timestamp with time zone
);
--> statement-breakpoint
CREATE INDEX "domain_events_undispatched_idx" ON "domain_events" ("occurred_at") WHERE "dispatched_at" IS NULL;--> statement-breakpoint
CREATE INDEX "domain_events_task_idx" ON "domain_events" ("task_instance_id");--> statement-breakpoint
CREATE UNIQUE INDEX "notifications_event_person_key" ON "notifications" ("event_id","person_id");--> statement-breakpoint
CREATE INDEX "notifications_person_idx" ON "notifications" ("person_id","read_at","created_at");--> statement-breakpoint
ALTER TABLE "domain_events" ADD CONSTRAINT "domain_events_task_instance_id_task_instances_id_fkey" FOREIGN KEY ("task_instance_id") REFERENCES "task_instances"("id");--> statement-breakpoint
ALTER TABLE "domain_events" ADD CONSTRAINT "domain_events_actor_person_id_people_id_fkey" FOREIGN KEY ("actor_person_id") REFERENCES "people"("id");--> statement-breakpoint
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_person_id_people_id_fkey" FOREIGN KEY ("person_id") REFERENCES "people"("id");--> statement-breakpoint
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_event_id_domain_events_id_fkey" FOREIGN KEY ("event_id") REFERENCES "domain_events"("id");--> statement-breakpoint
ALTER TABLE "notifications" ADD CONSTRAINT "notifications_task_instance_id_task_instances_id_fkey" FOREIGN KEY ("task_instance_id") REFERENCES "task_instances"("id");