-- Additive persistence split for planning demand vs assignment
-- Run: psql $DATABASE_URL -f packages/db/prisma/migrations/20260313_demand_assignment_additive.sql

CREATE TABLE IF NOT EXISTS demand_requirements (
  id text PRIMARY KEY,
  "legacyAllocationId" text UNIQUE,
  "projectId" text NOT NULL REFERENCES projects(id),
  "startDate" date NOT NULL,
  "endDate" date NOT NULL,
  "hoursPerDay" double precision NOT NULL,
  percentage double precision NOT NULL,
  role text,
  "roleId" text REFERENCES roles(id),
  headcount integer NOT NULL DEFAULT 1,
  status "AllocationStatus" NOT NULL DEFAULT 'PROPOSED',
  metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
  "createdAt" timestamptz NOT NULL DEFAULT now(),
  "updatedAt" timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE IF NOT EXISTS assignments (
  id text PRIMARY KEY,
  "legacyAllocationId" text UNIQUE,
  "demandRequirementId" text REFERENCES demand_requirements(id),
  "resourceId" text NOT NULL REFERENCES resources(id),
  "projectId" text NOT NULL REFERENCES projects(id),
  "startDate" date NOT NULL,
  "endDate" date NOT NULL,
  "hoursPerDay" double precision NOT NULL,
  percentage double precision NOT NULL,
  role text,
  "roleId" text REFERENCES roles(id),
  "dailyCostCents" integer NOT NULL,
  status "AllocationStatus" NOT NULL DEFAULT 'PROPOSED',
  metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
  "createdAt" timestamptz NOT NULL DEFAULT now(),
  "updatedAt" timestamptz NOT NULL DEFAULT now()
);

CREATE UNIQUE INDEX IF NOT EXISTS unique_assignment
  ON assignments ("resourceId", "projectId", "startDate", "endDate");

CREATE INDEX IF NOT EXISTS idx_demand_requirements_legacy_allocation_id
  ON demand_requirements ("legacyAllocationId");

CREATE INDEX IF NOT EXISTS idx_demand_requirements_project_id
  ON demand_requirements ("projectId");

CREATE INDEX IF NOT EXISTS idx_demand_requirements_start_end
  ON demand_requirements ("startDate", "endDate");

CREATE INDEX IF NOT EXISTS idx_demand_requirements_status
  ON demand_requirements (status);

CREATE INDEX IF NOT EXISTS idx_assignments_legacy_allocation_id
  ON assignments ("legacyAllocationId");

CREATE INDEX IF NOT EXISTS idx_assignments_demand_requirement_id
  ON assignments ("demandRequirementId");

CREATE INDEX IF NOT EXISTS idx_assignments_resource_id
  ON assignments ("resourceId");

CREATE INDEX IF NOT EXISTS idx_assignments_project_id
  ON assignments ("projectId");

CREATE INDEX IF NOT EXISTS idx_assignments_start_end
  ON assignments ("startDate", "endDate");

CREATE INDEX IF NOT EXISTS idx_assignments_status
  ON assignments (status);
