DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_type
        WHERE typname = 'online_lesson_status'
    ) THEN
        CREATE TYPE "public"."online_lesson_status" AS ENUM('draft', 'published', 'archived');
    END IF;
END $$;--> statement-breakpoint

CREATE TABLE IF NOT EXISTS "online_lessons" (
	"id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
	"organization_id" text NOT NULL,
	"title" text NOT NULL,
	"description" text,
	"category" text,
	"video_url" text,
	"video_file_name" text,
	"video_file_type" text,
	"video_file_size" integer,
	"video_storage_key" text,
	"video_file_url" text,
	"attachment_file_name" text,
	"attachment_file_type" text,
	"attachment_file_size" integer,
	"attachment_storage_key" text,
	"attachment_file_url" text,
	"thumbnail_file_name" text,
	"thumbnail_file_type" text,
	"thumbnail_file_size" integer,
	"thumbnail_storage_key" text,
	"thumbnail_url" text,
	"status" "online_lesson_status" DEFAULT 'draft' NOT NULL,
	"is_published" boolean DEFAULT false NOT NULL,
	"published_at" timestamp with time zone,
	"created_by" text NOT NULL,
	"updated_by" text,
	"created_at" timestamp with time zone DEFAULT now() NOT NULL,
	"updated_at" timestamp with time zone DEFAULT now() NOT NULL
);--> statement-breakpoint

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'online_lessons_organization_id_organizations_id_fk'
    ) THEN
        ALTER TABLE "online_lessons"
        ADD CONSTRAINT "online_lessons_organization_id_organizations_id_fk"
        FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;
    END IF;
END $$;--> statement-breakpoint

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'online_lessons_created_by_users_id_fk'
    ) THEN
        ALTER TABLE "online_lessons"
        ADD CONSTRAINT "online_lessons_created_by_users_id_fk"
        FOREIGN KEY ("created_by") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;
    END IF;
END $$;--> statement-breakpoint

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'online_lessons_updated_by_users_id_fk'
    ) THEN
        ALTER TABLE "online_lessons"
        ADD CONSTRAINT "online_lessons_updated_by_users_id_fk"
        FOREIGN KEY ("updated_by") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
    END IF;
END $$;
