-- ============================================
-- CRM v2 - Unified Deals Table
-- Execute: psql -h localhost -U gbuser -d botserver -f crm2_setup.sql
-- ============================================

-- 1. Drop old tables (never used in production)
DROP TABLE IF EXISTS crm_leads CASCADE;
DROP TABLE IF EXISTS crm_opportunities CASCADE;

-- 2. Create domain: segments
CREATE TABLE crm_deal_segments (
  id          uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  org_id      uuid NOT NULL,
  bot_id      uuid NOT NULL,
  name        varchar(50) NOT NULL,
  description varchar(255),
  created_at  timestamptz DEFAULT now()
);

-- Insert default segments
INSERT INTO crm_deal_segments (org_id, bot_id, name) 
SELECT org_id, bot_id, name FROM crm_pipeline_stages LIMIT 1;

-- 3. Create main deals table
CREATE TABLE crm_deals (
  -- 🆔 Key
  id              uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  org_id          uuid NOT NULL,
  bot_id          uuid NOT NULL,

  -- 🔗 Links to Contact/Account (NO DUPLICATE!)
  contact_id      uuid REFERENCES crm_contacts(id),
  account_id      uuid REFERENCES crm_accounts(id),
  
  -- 🔗 Owner/Team (FK to users)
  owner_id        uuid REFERENCES users(id),
  assignedto_id   uuid REFERENCES users(id),
  am_id           uuid REFERENCES users(id),
  
  -- 💰 Deal
  description     text,
  value           numeric(15,2),
  
  -- 📊 Pipeline (use existing crm_pipeline_stages!)
  stage_id        uuid REFERENCES crm_pipeline_stages(id),
  probability     integer DEFAULT 0,
  
  -- 🎯 Classification
  source          varchar(50),  -- EMAIL, CALL, WEBSITE, REFERAL
  segment_id      uuid REFERENCES crm_deal_segments(id),
  territory       varchar(30),
  
  -- 📅 Dates
  expected_close_date date,
  period           integer,  -- 1=manhã, 2=tarde, 3=noite (or hour 1-24)
  deal_date       date,
  created_at      timestamptz DEFAULT now(),
  updated_at      timestamptz,
  
  -- 🌐 Social
  linkedin        varchar(100),
  facebook        varchar(80),
  twitter         varchar(30),
  instagram       varchar(50),
  
  -- 📝 Notes (only current, history goes to crm_activities)
  notes           text,
  
  -- 🏷️ Tags
  tags            text[],
  
  -- 🔍 Flags
  hard_to_find    boolean DEFAULT false,
  
  -- 📦 Custom Fields (remaining ~50 fields from gb.rob)
  custom_fields   jsonb DEFAULT '{}'
);

-- 4. Add deal_id to crm_activities (for history migration)
ALTER TABLE crm_activities ADD COLUMN IF NOT EXISTS deal_id uuid REFERENCES crm_deals(id);

-- 5. Create indexes
CREATE INDEX idx_crm_deals_org_bot ON crm_deals(org_id, bot_id);
CREATE INDEX idx_crm_deals_contact ON crm_deals(contact_id);
CREATE INDEX idx_crm_deals_account ON crm_deals(account_id);
CREATE INDEX idx_crm_deals_stage ON crm_deals(stage_id);
CREATE INDEX idx_crm_deals_owner ON crm_deals(owner_id);
CREATE INDEX idx_crm_deals_source ON crm_deals(source);
CREATE INDEX idx_crm_deals_company ON crm_deals(company);

-- 6. Grant permissions
GRANT ALL ON crm_deals TO gbuser;
GRANT ALL ON crm_deal_segments TO gbuser;
