-- CreateEnum
CREATE TYPE "public"."MarketingSyncRunStatus" AS ENUM ('queued', 'running', 'success', 'failed');

-- CreateEnum
CREATE TYPE "public"."EmploymentStatus" AS ENUM ('active', 'leave', 'terminated');

-- CreateEnum
CREATE TYPE "public"."EmployeeLifecycleEventType" AS ENUM ('hire', 'transfer', 'leave', 'termination', 'rehire');

-- CreateEnum
CREATE TYPE "public"."HrUpdateSeverity" AS ENUM ('info', 'warning', 'critical');

-- CreateEnum
CREATE TYPE "public"."FactoryAssetState" AS ENUM ('draft', 'active', 'down', 'retired');

-- CreateEnum
CREATE TYPE "public"."PmTemplateState" AS ENUM ('draft', 'active', 'archived');

-- CreateEnum
CREATE TYPE "public"."PmWorkOrderState" AS ENUM ('draft', 'scheduled', 'in_progress', 'completed', 'verified', 'overdue', 'cancelled');

-- CreateEnum
CREATE TYPE "public"."ReminderEventState" AS ENUM ('queued', 'sent', 'acknowledged', 'escalated', 'failed');

-- CreateEnum
CREATE TYPE "public"."ApprovalState" AS ENUM ('draft', 'submitted', 'pending_owner', 'approved', 'rejected', 'changes_requested', 'cancelled');

-- CreateEnum
CREATE TYPE "public"."SalesForecastState" AS ENUM ('draft', 'published', 'superseded');

-- CreateEnum
CREATE TYPE "public"."ProductionPlanState" AS ENUM ('draft', 'simulated', 'locked', 'approved', 'released', 'replanned');

-- AlterTable
ALTER TABLE "public"."MarketingInitiative" ADD COLUMN     "attributionCampaign" TEXT,
ADD COLUMN     "attributionChannel" TEXT,
ADD COLUMN     "attributionEnd" TIMESTAMP(3),
ADD COLUMN     "attributionPageId" TEXT,
ADD COLUMN     "attributionStart" TIMESTAMP(3),
ADD COLUMN     "autoActual" DOUBLE PRECISION,
ADD COLUMN     "autoRevenueActual" DOUBLE PRECISION,
ADD COLUMN     "autoTicketsActual" INTEGER,
ADD COLUMN     "autoUpdatedAt" TIMESTAMP(3);

-- CreateTable
CREATE TABLE "public"."MarketingMetaConnection" (
    "id" TEXT NOT NULL,
    "department" "public"."DepartmentKey" NOT NULL DEFAULT 'marketing',
    "accountId" TEXT NOT NULL,
    "pageId" TEXT NOT NULL,
    "pageName" TEXT NOT NULL,
    "pageAccessToken" TEXT NOT NULL,
    "tokenExpiresAt" TIMESTAMP(3),
    "connectedById" TEXT,
    "isActive" BOOLEAN NOT NULL DEFAULT true,
    "lastSyncedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "public"."MarketingSocialMetricDaily" (
    "id" TEXT NOT NULL,
    "department" "public"."DepartmentKey" NOT NULL DEFAULT 'marketing',
    "connectionId" TEXT NOT NULL,
    "channel" TEXT NOT NULL,
    "metricDate" TIMESTAMP(3) NOT NULL,
    "followers" INTEGER NOT NULL,
    "reach" INTEGER NOT NULL,
    "impressions" INTEGER NOT NULL,
    "engagements" INTEGER NOT NULL,
    "engagementRate" DOUBLE PRECISION NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "public"."MarketingSyncRun" (
    "id" TEXT NOT NULL,
    "department" "public"."DepartmentKey" NOT NULL DEFAULT 'marketing',
    "connectionId" TEXT,
    "status" "public"."MarketingSyncRunStatus" NOT NULL DEFAULT 'queued',
    "message" TEXT,
    "rowsIngested" INTEGER NOT NULL DEFAULT 0,
    "triggeredById" TEXT,
    "startedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "completedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "public"."EmployeeProfile" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "employeeCode" TEXT,
    "hireDate" TIMESTAMP(3),
    "employmentType" TEXT,
    "managerUserId" TEXT,
    "locationId" TEXT,
    "fte" DOUBLE PRECISION NOT NULL DEFAULT 1,
    "employmentStatus" "public"."EmploymentStatus" NOT NULL DEFAULT 'active',
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "public"."EmployeeLifecycleEvent" (
    "id" TEXT NOT NULL,
    "userId" TEXT NOT NULL,
    "eventType" "public"."EmployeeLifecycleEventType" NOT NULL,
    "effectiveAt" TIMESTAMP(3) NOT NULL,
    "reason" TEXT,
    "isVoluntary" BOOLEAN,
    "metadata" JSONB,
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "public"."HrMetricSnapshot" (
    "id" TEXT NOT NULL,
    "department" "public"."DepartmentKey",
    "snapshotDate" TIMESTAMP(3) NOT NULL,
    "headcount" INTEGER NOT NULL,
    "hires" INTEGER NOT NULL,
    "exits" INTEGER NOT NULL,
    "churnPct" DOUBLE PRECISION NOT NULL,
    "medianTenureMonths" DOUBLE PRECISION NOT NULL,
    "peopleHealthScore" DOUBLE PRECISION NOT NULL,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "public"."HrUpdate" (
    "id" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "body" TEXT NOT NULL,
    "severity" "public"."HrUpdateSeverity" NOT NULL DEFAULT 'info',
    "audience" TEXT NOT NULL DEFAULT 'hc_leadership',
    "status" TEXT NOT NULL DEFAULT 'draft',
    "publishedAt" TIMESTAMP(3),
    "authorId" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "public"."FactoryAsset" (
    "id" TEXT NOT NULL,
    "department" "public"."DepartmentKey" NOT NULL DEFAULT 'operaciones',
    "assetCode" TEXT NOT NULL,
    "name" TEXT NOT NULL,
    "category" TEXT NOT NULL,
    "locationId" TEXT,
    "criticality" INTEGER NOT NULL DEFAULT 3,
    "state" "public"."FactoryAssetState" NOT NULL DEFAULT 'active',
    "serviceStrategy" TEXT,
    "lastMaintenanceAt" TIMESTAMP(3),
    "nextMaintenanceAt" TIMESTAMP(3),
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "public"."PmTemplate" (
    "id" TEXT NOT NULL,
    "assetId" TEXT NOT NULL,
    "title" TEXT NOT NULL,
    "description" TEXT,
    "cadenceDays" INTEGER,
    "cadenceHours" INTEGER,
    "state" "public"."PmTemplateState" NOT NULL DEFAULT 'active',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "public"."PmWorkOrder" (
    "id" TEXT NOT NULL,
    "assetId" TEXT NOT NULL,
    "templateId" TEXT,
    "title" TEXT NOT NULL,
    "description" TEXT,
    "scheduledFor" TIMESTAMP(3) NOT NULL,
    "dueBy" TIMESTAMP(3) NOT NULL,
    "startedAt" TIMESTAMP(3),
    "completedAt" TIMESTAMP(3),
    "estimatedCost" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "expectedDowntimeHours" DOUBLE PRECISION NOT NULL DEFAULT 0,
    "actualCost" DOUBLE PRECISION,
    "actualDowntimeHours" DOUBLE PRECISION,
    "state" "public"."PmWorkOrderState" NOT NULL DEFAULT 'scheduled',
    "requestedById" TEXT,
    "approvedById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "public"."ReminderEvent" (
    "id" TEXT NOT NULL,
    "workOrderId" TEXT NOT NULL,
    "remindAt" TIMESTAMP(3) NOT NULL,
    "channel" TEXT NOT NULL DEFAULT 'in_app',
    "message" TEXT,
    "state" "public"."ReminderEventState" NOT NULL DEFAULT 'queued',
    "acknowledgedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

-- CreateTable
CREATE TABLE "public"."MaintenanceApprovalPolicy" (
    "id" TEXT NOT NULL,
    "department" "public"."DepartmentKey" NOT NULL DEFAULT 'operaciones',
    "costThreshold" DOUBLE PRECISION NOT NULL DEFAULT 5000,
    "downtimeThresholdHours" DOUBLE PRECISION NOT NULL DEFAULT 4,
    "ownerUserId" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "public"."SalesForecast" (
    "id" TEXT NOT NULL,
    "department" "public"."DepartmentKey" NOT NULL DEFAULT 'operaciones',
    "weekStart" TIMESTAMP(3) NOT NULL,
    "weekEnd" TIMESTAMP(3) NOT NULL,
    "locationId" TEXT,
    "sku" TEXT,
    "forecastUnits" DOUBLE PRECISION NOT NULL,
    "multiplier" DOUBLE PRECISION NOT NULL DEFAULT 1.2,
    "state" "public"."SalesForecastState" NOT NULL DEFAULT 'draft',
    "createdById" TEXT,
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "public"."ProductionPlan" (
    "id" TEXT NOT NULL,
    "department" "public"."DepartmentKey" NOT NULL DEFAULT 'operaciones',
    "weekStart" TIMESTAMP(3) NOT NULL,
    "weekEnd" TIMESTAMP(3) NOT NULL,
    "lineName" TEXT NOT NULL,
    "plannedUnits" DOUBLE PRECISION NOT NULL,
    "forecastUnits" DOUBLE PRECISION NOT NULL,
    "capacityUnits" DOUBLE PRECISION NOT NULL,
    "varianceUnits" DOUBLE PRECISION NOT NULL,
    "state" "public"."ProductionPlanState" NOT NULL DEFAULT 'draft',
    "createdById" TEXT,
    "approvedById" TEXT,
    "approvedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateTable
CREATE TABLE "public"."ApprovalRequest" (
    "id" TEXT NOT NULL,
    "department" "public"."DepartmentKey" NOT NULL DEFAULT 'operaciones',
    "requestType" TEXT NOT NULL,
    "workOrderId" TEXT,
    "productionPlanId" TEXT,
    "submittedById" TEXT,
    "approverId" TEXT,
    "state" "public"."ApprovalState" NOT NULL DEFAULT 'submitted',
    "reason" TEXT,
    "decidedAt" TIMESTAMP(3),
    "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
    "updatedAt" TIMESTAMP(3) NOT NULL,

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

-- CreateIndex
CREATE INDEX "MarketingMetaConnection_department_isActive_idx" ON "public"."MarketingMetaConnection"("department", "isActive");

-- CreateIndex
CREATE UNIQUE INDEX "MarketingMetaConnection_department_pageId_isActive_key" ON "public"."MarketingMetaConnection"("department", "pageId", "isActive");

-- CreateIndex
CREATE INDEX "MarketingSocialMetricDaily_department_channel_metricDate_idx" ON "public"."MarketingSocialMetricDaily"("department", "channel", "metricDate");

-- CreateIndex
CREATE UNIQUE INDEX "MarketingSocialMetricDaily_connectionId_channel_metricDate_key" ON "public"."MarketingSocialMetricDaily"("connectionId", "channel", "metricDate");

-- CreateIndex
CREATE INDEX "MarketingSyncRun_department_createdAt_idx" ON "public"."MarketingSyncRun"("department", "createdAt");

-- CreateIndex
CREATE INDEX "MarketingSyncRun_status_createdAt_idx" ON "public"."MarketingSyncRun"("status", "createdAt");

-- CreateIndex
CREATE UNIQUE INDEX "EmployeeProfile_userId_key" ON "public"."EmployeeProfile"("userId");

-- CreateIndex
CREATE INDEX "EmployeeProfile_employmentStatus_hireDate_idx" ON "public"."EmployeeProfile"("employmentStatus", "hireDate");

-- CreateIndex
CREATE INDEX "EmployeeLifecycleEvent_userId_effectiveAt_idx" ON "public"."EmployeeLifecycleEvent"("userId", "effectiveAt");

-- CreateIndex
CREATE INDEX "EmployeeLifecycleEvent_eventType_effectiveAt_idx" ON "public"."EmployeeLifecycleEvent"("eventType", "effectiveAt");

-- CreateIndex
CREATE INDEX "HrMetricSnapshot_snapshotDate_department_idx" ON "public"."HrMetricSnapshot"("snapshotDate", "department");

-- CreateIndex
CREATE INDEX "HrUpdate_status_publishedAt_idx" ON "public"."HrUpdate"("status", "publishedAt");

-- CreateIndex
CREATE UNIQUE INDEX "FactoryAsset_assetCode_key" ON "public"."FactoryAsset"("assetCode");

-- CreateIndex
CREATE INDEX "FactoryAsset_department_state_idx" ON "public"."FactoryAsset"("department", "state");

-- CreateIndex
CREATE INDEX "FactoryAsset_nextMaintenanceAt_state_idx" ON "public"."FactoryAsset"("nextMaintenanceAt", "state");

-- CreateIndex
CREATE INDEX "PmTemplate_assetId_state_idx" ON "public"."PmTemplate"("assetId", "state");

-- CreateIndex
CREATE INDEX "PmWorkOrder_assetId_state_dueBy_idx" ON "public"."PmWorkOrder"("assetId", "state", "dueBy");

-- CreateIndex
CREATE INDEX "PmWorkOrder_state_scheduledFor_idx" ON "public"."PmWorkOrder"("state", "scheduledFor");

-- CreateIndex
CREATE INDEX "ReminderEvent_workOrderId_state_idx" ON "public"."ReminderEvent"("workOrderId", "state");

-- CreateIndex
CREATE INDEX "ReminderEvent_remindAt_state_idx" ON "public"."ReminderEvent"("remindAt", "state");

-- CreateIndex
CREATE UNIQUE INDEX "MaintenanceApprovalPolicy_department_key" ON "public"."MaintenanceApprovalPolicy"("department");

-- CreateIndex
CREATE INDEX "SalesForecast_department_weekStart_state_idx" ON "public"."SalesForecast"("department", "weekStart", "state");

-- CreateIndex
CREATE INDEX "ProductionPlan_department_weekStart_state_idx" ON "public"."ProductionPlan"("department", "weekStart", "state");

-- CreateIndex
CREATE INDEX "ApprovalRequest_department_state_createdAt_idx" ON "public"."ApprovalRequest"("department", "state", "createdAt");

-- AddForeignKey
ALTER TABLE "public"."MarketingSocialMetricDaily" ADD CONSTRAINT "MarketingSocialMetricDaily_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "public"."MarketingMetaConnection"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."MarketingSyncRun" ADD CONSTRAINT "MarketingSyncRun_connectionId_fkey" FOREIGN KEY ("connectionId") REFERENCES "public"."MarketingMetaConnection"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."EmployeeProfile" ADD CONSTRAINT "EmployeeProfile_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."EmployeeLifecycleEvent" ADD CONSTRAINT "EmployeeLifecycleEvent_userId_fkey" FOREIGN KEY ("userId") REFERENCES "public"."User"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."EmployeeLifecycleEvent" ADD CONSTRAINT "EmployeeLifecycleEvent_createdById_fkey" FOREIGN KEY ("createdById") REFERENCES "public"."User"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."HrUpdate" ADD CONSTRAINT "HrUpdate_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "public"."User"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."PmTemplate" ADD CONSTRAINT "PmTemplate_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "public"."FactoryAsset"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."PmWorkOrder" ADD CONSTRAINT "PmWorkOrder_assetId_fkey" FOREIGN KEY ("assetId") REFERENCES "public"."FactoryAsset"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."PmWorkOrder" ADD CONSTRAINT "PmWorkOrder_templateId_fkey" FOREIGN KEY ("templateId") REFERENCES "public"."PmTemplate"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."ReminderEvent" ADD CONSTRAINT "ReminderEvent_workOrderId_fkey" FOREIGN KEY ("workOrderId") REFERENCES "public"."PmWorkOrder"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."ApprovalRequest" ADD CONSTRAINT "ApprovalRequest_workOrderId_fkey" FOREIGN KEY ("workOrderId") REFERENCES "public"."PmWorkOrder"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "public"."ApprovalRequest" ADD CONSTRAINT "ApprovalRequest_productionPlanId_fkey" FOREIGN KEY ("productionPlanId") REFERENCES "public"."ProductionPlan"("id") ON DELETE SET NULL ON UPDATE CASCADE;
