-- CEO OS: Contacts (CRM), Risks (Risk Register), Projects
-- Migration 0010_ceo_os_features

--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "contacts" (
  "id" uuid DEFAULT gen_random_uuid() PRIMARY KEY NOT NULL,
  "tenant_id" uuid NOT NULL,
  "workspace_id" uuid,
  "organization_id" uuid,
  "full_name" text NOT NULL,
  "email" text,
  "phone" text,
  "role" text,
  "linkedin_url" text,
  "notes" text,
  "tags" text[] DEFAULT '{}' NOT NULL,
  "source" text,
  "consent_status" text DEFAULT 'unknown' NOT NULL,
  "created_at" timestamp DEFAULT now() NOT NULL,
  "updated_at" timestamp DEFAULT now() NOT NULL,
  "deleted_at" timestamp
);

--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "risks" (
  "id" uuid DEFAULT gen_random_uuid() PRIMARY KEY NOT NULL,
  "tenant_id" uuid NOT NULL,
  "workspace_id" uuid,
  "title" text NOT NULL,
  "description" text,
  "category" text,
  "probability" text DEFAULT 'medium' NOT NULL,
  "impact" text DEFAULT 'medium' NOT NULL,
  "risk_score" integer GENERATED ALWAYS AS (
    CASE probability
      WHEN 'low'      THEN 1
      WHEN 'medium'   THEN 2
      WHEN 'high'     THEN 3
      WHEN 'critical' THEN 4
      ELSE 2
    END *
    CASE impact
      WHEN 'low'      THEN 1
      WHEN 'medium'   THEN 2
      WHEN 'high'     THEN 3
      WHEN 'critical' THEN 4
      ELSE 2
    END
  ) STORED,
  "status" text DEFAULT 'open' NOT NULL,
  "mitigation" text,
  "owner" text,
  "decision_id" uuid,
  "review_due_at" timestamp,
  "created_at" timestamp DEFAULT now() NOT NULL,
  "updated_at" timestamp DEFAULT now() NOT NULL
);

--> statement-breakpoint
CREATE TABLE IF NOT EXISTS "projects" (
  "id" uuid DEFAULT gen_random_uuid() PRIMARY KEY NOT NULL,
  "tenant_id" uuid NOT NULL,
  "workspace_id" uuid,
  "organization_id" uuid,
  "name" text NOT NULL,
  "description" text,
  "status" text DEFAULT 'planning' NOT NULL,
  "priority" text DEFAULT 'medium' NOT NULL,
  "start_date" date,
  "due_date" date,
  "budget_minor_units" bigint,
  "currency" text DEFAULT 'RON',
  "tags" text[] DEFAULT '{}' NOT NULL,
  "created_at" timestamp DEFAULT now() NOT NULL,
  "updated_at" timestamp DEFAULT now() NOT NULL,
  "deleted_at" timestamp
);
