-- ============================================================
-- Company Detail Overhaul - Schema Migration
-- ============================================================
-- Neue Tabellen: industries, account_types, relationship_types,
--                company_relationships, contracts
-- Neue Enums: ContractStatus
-- Erweiterte Tabellen: companies (industryId, accountTypeId, ownerId),
--                      activities (contactId optional, companyId neu)
-- ============================================================

-- ContractStatus Enum
CREATE TYPE "app_crm"."ContractStatus" AS ENUM ('DRAFT', 'ACTIVE', 'EXPIRED', 'CANCELLED');

-- --------------------------------------------------------
-- Industries (Branchen, admin-konfigurierbar)
-- --------------------------------------------------------
CREATE TABLE "app_crm"."industries" (
  "id" UUID NOT NULL DEFAULT gen_random_uuid(),
  "tenant_id" UUID NOT NULL,
  "name" VARCHAR(100) NOT NULL,
  "color" VARCHAR(7) NOT NULL DEFAULT '#6B7280',
  "sort_order" INTEGER NOT NULL DEFAULT 0,
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at" TIMESTAMP(3) NOT NULL,

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

CREATE UNIQUE INDEX "industries_tenant_id_name_key"
  ON "app_crm"."industries"("tenant_id", "name");

CREATE INDEX "industries_tenant_id_idx"
  ON "app_crm"."industries"("tenant_id");

-- --------------------------------------------------------
-- AccountTypes (Kontotypen, admin-konfigurierbar)
-- --------------------------------------------------------
CREATE TABLE "app_crm"."account_types" (
  "id" UUID NOT NULL DEFAULT gen_random_uuid(),
  "tenant_id" UUID NOT NULL,
  "name" VARCHAR(100) NOT NULL,
  "sort_order" INTEGER NOT NULL DEFAULT 0,
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at" TIMESTAMP(3) NOT NULL,

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

CREATE UNIQUE INDEX "account_types_tenant_id_name_key"
  ON "app_crm"."account_types"("tenant_id", "name");

CREATE INDEX "account_types_tenant_id_idx"
  ON "app_crm"."account_types"("tenant_id");

-- --------------------------------------------------------
-- RelationshipTypes (Beziehungstypen, admin-konfigurierbar)
-- --------------------------------------------------------
CREATE TABLE "app_crm"."relationship_types" (
  "id" UUID NOT NULL DEFAULT gen_random_uuid(),
  "tenant_id" UUID NOT NULL,
  "name" VARCHAR(100) NOT NULL,
  "sort_order" INTEGER NOT NULL DEFAULT 0,
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at" TIMESTAMP(3) NOT NULL,

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

CREATE UNIQUE INDEX "relationship_types_tenant_id_name_key"
  ON "app_crm"."relationship_types"("tenant_id", "name");

CREATE INDEX "relationship_types_tenant_id_idx"
  ON "app_crm"."relationship_types"("tenant_id");

-- --------------------------------------------------------
-- Company: Neue Felder hinzufuegen
-- --------------------------------------------------------
ALTER TABLE "app_crm"."companies"
  ADD COLUMN "industry_id" UUID,
  ADD COLUMN "account_type_id" UUID,
  ADD COLUMN "owner_id" UUID,
  ADD COLUMN "owner_name" VARCHAR(200);

-- Indizes fuer neue FK-Felder
CREATE INDEX "companies_tenant_id_industry_id_idx"
  ON "app_crm"."companies"("tenant_id", "industry_id");

CREATE INDEX "companies_tenant_id_account_type_id_idx"
  ON "app_crm"."companies"("tenant_id", "account_type_id");

-- Foreign Keys
ALTER TABLE "app_crm"."companies"
  ADD CONSTRAINT "companies_industry_id_fkey"
    FOREIGN KEY ("industry_id") REFERENCES "app_crm"."industries"("id") ON DELETE SET NULL ON UPDATE CASCADE;

ALTER TABLE "app_crm"."companies"
  ADD CONSTRAINT "companies_account_type_id_fkey"
    FOREIGN KEY ("account_type_id") REFERENCES "app_crm"."account_types"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- --------------------------------------------------------
-- Activity: contactId optional machen, companyId hinzufuegen
-- --------------------------------------------------------
ALTER TABLE "app_crm"."activities"
  ALTER COLUMN "contact_id" DROP NOT NULL;

ALTER TABLE "app_crm"."activities"
  ADD COLUMN "company_id" UUID;

-- Index fuer companyId
CREATE INDEX "activities_tenant_id_company_id_idx"
  ON "app_crm"."activities"("tenant_id", "company_id");

-- Foreign Key fuer companyId
ALTER TABLE "app_crm"."activities"
  ADD CONSTRAINT "activities_company_id_fkey"
    FOREIGN KEY ("company_id") REFERENCES "app_crm"."companies"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- --------------------------------------------------------
-- CompanyRelationship (N:M Beziehungen zwischen Unternehmen)
-- --------------------------------------------------------
CREATE TABLE "app_crm"."company_relationships" (
  "id" UUID NOT NULL DEFAULT gen_random_uuid(),
  "tenant_id" UUID NOT NULL,
  "company_id" UUID NOT NULL,
  "related_company_id" UUID NOT NULL,
  "relationship_type_id" UUID NOT NULL,
  "notes" TEXT,
  "created_by" UUID NOT NULL,
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

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

CREATE UNIQUE INDEX "company_relationships_company_id_related_company_id_relationship_type_id_key"
  ON "app_crm"."company_relationships"("company_id", "related_company_id", "relationship_type_id");

CREATE INDEX "company_relationships_tenant_id_idx"
  ON "app_crm"."company_relationships"("tenant_id");

CREATE INDEX "company_relationships_tenant_id_company_id_idx"
  ON "app_crm"."company_relationships"("tenant_id", "company_id");

CREATE INDEX "company_relationships_tenant_id_related_company_id_idx"
  ON "app_crm"."company_relationships"("tenant_id", "related_company_id");

ALTER TABLE "app_crm"."company_relationships"
  ADD CONSTRAINT "company_relationships_company_id_fkey"
    FOREIGN KEY ("company_id") REFERENCES "app_crm"."companies"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "app_crm"."company_relationships"
  ADD CONSTRAINT "company_relationships_related_company_id_fkey"
    FOREIGN KEY ("related_company_id") REFERENCES "app_crm"."companies"("id") ON DELETE CASCADE ON UPDATE CASCADE;

ALTER TABLE "app_crm"."company_relationships"
  ADD CONSTRAINT "company_relationships_relationship_type_id_fkey"
    FOREIGN KEY ("relationship_type_id") REFERENCES "app_crm"."relationship_types"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- --------------------------------------------------------
-- Contract (Vertraege - Platzhalter)
-- --------------------------------------------------------
CREATE TABLE "app_crm"."contracts" (
  "id" UUID NOT NULL DEFAULT gen_random_uuid(),
  "tenant_id" UUID NOT NULL,
  "company_id" UUID NOT NULL,
  "title" VARCHAR(255) NOT NULL,
  "status" "app_crm"."ContractStatus" NOT NULL DEFAULT 'DRAFT',
  "start_date" TIMESTAMP(3),
  "end_date" TIMESTAMP(3),
  "value" DECIMAL(15,2),
  "currency" VARCHAR(3) NOT NULL DEFAULT 'EUR',
  "notes" TEXT,
  "created_by" UUID NOT NULL,
  "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
  "updated_at" TIMESTAMP(3) NOT NULL,

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

CREATE INDEX "contracts_tenant_id_company_id_idx"
  ON "app_crm"."contracts"("tenant_id", "company_id");

ALTER TABLE "app_crm"."contracts"
  ADD CONSTRAINT "contracts_company_id_fkey"
    FOREIGN KEY ("company_id") REFERENCES "app_crm"."companies"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- --------------------------------------------------------
-- Daten-Migration: Bestehende industry-Freitext-Werte migrieren
-- --------------------------------------------------------
-- Hinweis: Diese Migration erstellt Industry-Records aus bestehenden
-- Freitext-Werten. Das alte industry-Feld bleibt bestehen als Fallback.
-- In einer spaeteren Migration kann es entfernt werden.

-- Schritt 1: Unique industry-Werte als Industry-Records erstellen
INSERT INTO "app_crm"."industries" ("id", "tenant_id", "name", "color", "sort_order", "created_at", "updated_at")
SELECT
  gen_random_uuid(),
  c."tenant_id",
  c."industry",
  '#6B7280',
  0,
  NOW(),
  NOW()
FROM (
  SELECT DISTINCT "tenant_id", "industry"
  FROM "app_crm"."companies"
  WHERE "industry" IS NOT NULL AND "industry" != ''
) c
ON CONFLICT ("tenant_id", "name") DO NOTHING;

-- Schritt 2: industry_id auf Companies setzen
UPDATE "app_crm"."companies" co
SET "industry_id" = i."id"
FROM "app_crm"."industries" i
WHERE co."tenant_id" = i."tenant_id"
  AND co."industry" = i."name"
  AND co."industry" IS NOT NULL
  AND co."industry" != '';
