-- ============================================================
-- Migration 010: Agenda geral de contatos
-- Tabela: agenda_contatos
-- ============================================================

CREATE TABLE IF NOT EXISTS agenda_contatos (
  chat_id VARCHAR(255) PRIMARY KEY,
  phone VARCHAR(80) NOT NULL,
  name VARCHAR(255),
  company VARCHAR(255),
  note TEXT,
  updated_by_user_id INTEGER REFERENCES usuarios(id) ON DELETE SET NULL,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);

DO $$
BEGIN
  IF to_regclass('public.customer_contacts') IS NOT NULL THEN
    INSERT INTO agenda_contatos (
      chat_id, phone, name, company, note, updated_by_user_id, created_at, updated_at
    )
    SELECT chat_id, phone, name, company, note, updated_by_user_id, created_at, updated_at
    FROM customer_contacts
    ON CONFLICT (chat_id) DO UPDATE SET
      phone = EXCLUDED.phone,
      name = EXCLUDED.name,
      company = EXCLUDED.company,
      note = EXCLUDED.note,
      updated_by_user_id = EXCLUDED.updated_by_user_id,
      updated_at = EXCLUDED.updated_at;
  END IF;
END $$;

CREATE INDEX IF NOT EXISTS idx_agenda_contatos_updated_at
  ON agenda_contatos (updated_at DESC);
