-- CreateSchema
CREATE SCHEMA IF NOT EXISTS "public";

-- CreateEnum
CREATE TYPE "RawSegmentStatus" AS ENUM ('PENDING', 'PROCESSED', 'DISCARDED');

-- CreateEnum
CREATE TYPE "CandidateSegmentStatus" AS ENUM ('PENDING_STT', 'TRANSCRIBED', 'FAILED');

-- CreateTable
CREATE TABLE "channels" (
    "id" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "youtube_handle" TEXT NOT NULL,
    "channel_id" TEXT NOT NULL,
    "is_active" BOOLEAN NOT NULL DEFAULT true,
    "last_checked_at" TIMESTAMP(3),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "channels_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "stream_sessions" (
    "id" TEXT NOT NULL,
    "channel_id" TEXT NOT NULL,
    "live_video_id" TEXT,
    "started_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "ended_at" TIMESTAMP(3),
    "total_segments" INTEGER NOT NULL DEFAULT 0,

    CONSTRAINT "stream_sessions_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "raw_segments" (
    "id" TEXT NOT NULL,
    "session_id" TEXT NOT NULL,
    "file_path" TEXT NOT NULL,
    "duration" INTEGER NOT NULL,
    "started_at" TIMESTAMP(3) NOT NULL,
    "status" "RawSegmentStatus" NOT NULL DEFAULT 'PENDING',
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "raw_segments_pkey" PRIMARY KEY ("id")
);

-- CreateTable
CREATE TABLE "candidate_segments" (
    "id" TEXT NOT NULL,
    "raw_segment_id" TEXT NOT NULL,
    "start_sec" INTEGER NOT NULL,
    "end_sec" INTEGER NOT NULL,
    "audio_peak_score" DOUBLE PRECISION,
    "chat_velocity_score" DOUBLE PRECISION,
    "transcript_json" JSONB,
    "status" "CandidateSegmentStatus" NOT NULL DEFAULT 'PENDING_STT',
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

    CONSTRAINT "candidate_segments_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "channels_channel_id_key" ON "channels"("channel_id");

-- AddForeignKey
ALTER TABLE "stream_sessions" ADD CONSTRAINT "stream_sessions_channel_id_fkey" FOREIGN KEY ("channel_id") REFERENCES "channels"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "raw_segments" ADD CONSTRAINT "raw_segments_session_id_fkey" FOREIGN KEY ("session_id") REFERENCES "stream_sessions"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "candidate_segments" ADD CONSTRAINT "candidate_segments_raw_segment_id_fkey" FOREIGN KEY ("raw_segment_id") REFERENCES "raw_segments"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
