-- Phase 10: CRM Foundation - Expand leads table, add activities and reminders

-- ============ ALTER leads TABLE ============
ALTER TABLE "leads" ADD COLUMN "phone" text;
ALTER TABLE "leads" ADD COLUMN "company" text;
ALTER TABLE "leads" ADD COLUMN "status" text NOT NULL DEFAULT 'contacted';
ALTER TABLE "leads" ADD COLUMN "last_contact_date" timestamp with time zone;
ALTER TABLE "leads" ADD COLUMN "next_action" text;
ALTER TABLE "leads" ADD COLUMN "next_action_date" timestamp with time zone;
ALTER TABLE "leads" ADD COLUMN "notes" text;
ALTER TABLE "leads" ADD COLUMN "updated_at" timestamp with time zone NOT NULL DEFAULT now();

-- ============ CREATE activities TABLE ============
CREATE TABLE IF NOT EXISTS "activities" (
	"id" text PRIMARY KEY NOT NULL,
	"lead_id" text NOT NULL,
	"type" text NOT NULL,
	"duration_minutes" integer,
	"notes" text NOT NULL,
	"activity_date" timestamp with time zone NOT NULL,
	"created_at" timestamp with time zone NOT NULL DEFAULT now(),
	FOREIGN KEY ("lead_id") REFERENCES "leads"("id") ON DELETE cascade
);

-- ============ CREATE reminders TABLE ============
CREATE TABLE IF NOT EXISTS "reminders" (
	"id" text PRIMARY KEY NOT NULL,
	"lead_id" text NOT NULL,
	"title" text NOT NULL,
	"description" text,
	"due_date" timestamp with time zone NOT NULL,
	"completed_at" timestamp with time zone,
	"created_at" timestamp with time zone NOT NULL DEFAULT now(),
	FOREIGN KEY ("lead_id") REFERENCES "leads"("id") ON DELETE cascade
);

-- ============ CREATE INDEXES ============
CREATE INDEX IF NOT EXISTS "activities_lead_id" ON "activities"("lead_id");
CREATE INDEX IF NOT EXISTS "activities_activity_date" ON "activities"("activity_date");
CREATE INDEX IF NOT EXISTS "reminders_lead_id" ON "reminders"("lead_id");
CREATE INDEX IF NOT EXISTS "reminders_due_date" ON "reminders"("due_date");
CREATE INDEX IF NOT EXISTS "leads_status" ON "leads"("status");
CREATE INDEX IF NOT EXISTS "leads_last_contact_date" ON "leads"("last_contact_date");
