-- CreateEnum
CREATE TYPE "LeadType" AS ENUM ('BROKER', 'BUILDER', 'OTHER');

-- CreateEnum
CREATE TYPE "LeadSource" AS ENUM ('FORM', 'WHATSAPP', 'MANUAL');

-- CreateEnum
CREATE TYPE "LeadStage" AS ENUM ('NEW', 'CONTACTED', 'CALL_SCHEDULED', 'CALL_DONE', 'DEMO_ACTIVE', 'DEMO_ENDED', 'ON_HOLD', 'WON', 'LOST');

-- CreateEnum
CREATE TYPE "Channel" AS ENUM ('EMAIL', 'WHATSAPP');

-- CreateEnum
CREATE TYPE "SequenceStatus" AS ENUM ('PENDING', 'SENT', 'SKIPPED', 'PAUSED');

-- CreateEnum
CREATE TYPE "LostReason" AS ENUM ('PRICE', 'NOT_INTERESTED', 'NO_RESPONSE', 'COMPETITOR', 'OTHER');

-- CreateEnum
CREATE TYPE "TemplateLeadType" AS ENUM ('BROKER', 'BUILDER', 'OTHER', 'ALL');

-- CreateTable
CREATE TABLE "leads" (
    "id" TEXT NOT NULL,
    "name" VARCHAR(255) NOT NULL,
    "email" VARCHAR(255),
    "whatsapp" VARCHAR(20),
    "company" VARCHAR(255),
    "lead_type" "LeadType" NOT NULL,
    "lead_type_other" VARCHAR(255),
    "source" "LeadSource" NOT NULL,
    "stage" "LeadStage" NOT NULL DEFAULT 'NEW',
    "demo_start_date" TIMESTAMP(3),
    "demo_end_date" TIMESTAMP(3),
    "calendly_event_id" VARCHAR(255),
    "notes" TEXT,
    "lost_reason" "LostReason",
    "sequence_paused" BOOLEAN NOT NULL DEFAULT false,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updated_at" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "sequence_logs" (
    "id" TEXT NOT NULL,
    "lead_id" TEXT NOT NULL,
    "step_key" VARCHAR(100) NOT NULL,
    "channel" "Channel" NOT NULL,
    "status" "SequenceStatus" NOT NULL DEFAULT 'PENDING',
    "scheduled_at" TIMESTAMP(3) NOT NULL,
    "sent_at" TIMESTAMP(3),
    "skip_reason" VARCHAR(255),
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "email_templates" (
    "id" TEXT NOT NULL,
    "template_key" VARCHAR(100) NOT NULL,
    "lead_type" "TemplateLeadType" NOT NULL,
    "channel" "Channel" NOT NULL,
    "subject" TEXT,
    "body" TEXT NOT NULL,
    "is_active" BOOLEAN NOT NULL DEFAULT true,
    "updated_at" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "activity_logs" (
    "id" TEXT NOT NULL,
    "lead_id" TEXT NOT NULL,
    "type" VARCHAR(100) NOT NULL,
    "description" TEXT NOT NULL,
    "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateIndex
CREATE UNIQUE INDEX "email_templates_template_key_key" ON "email_templates"("template_key");

-- AddForeignKey
ALTER TABLE "sequence_logs" ADD CONSTRAINT "sequence_logs_lead_id_fkey" FOREIGN KEY ("lead_id") REFERENCES "leads"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "activity_logs" ADD CONSTRAINT "activity_logs_lead_id_fkey" FOREIGN KEY ("lead_id") REFERENCES "leads"("id") ON DELETE CASCADE ON UPDATE CASCADE;
