-- Add company_id to contacts table
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name='contacts' AND column_name='company_id'
    ) THEN
        ALTER TABLE contacts ADD COLUMN company_id UUID REFERENCES companies(id) ON DELETE SET NULL;
        CREATE INDEX idx_contacts_company_id ON contacts(company_id);
    END IF;
END $$;

-- Add reminder fields to notes table
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name='notes' AND column_name='reminder_date'
    ) THEN
        ALTER TABLE notes ADD COLUMN reminder_date TIMESTAMP;
        CREATE INDEX idx_notes_reminder_date ON notes(reminder_date) WHERE reminder_date IS NOT NULL;
    END IF;

    IF NOT EXISTS (
        SELECT 1 FROM information_schema.columns
        WHERE table_name='notes' AND column_name='reminder_sent'
    ) THEN
        ALTER TABLE notes ADD COLUMN reminder_sent BOOLEAN NOT NULL DEFAULT false;
        CREATE INDEX idx_notes_reminder_pending ON notes(reminder_date, reminder_sent) WHERE reminder_date IS NOT NULL AND reminder_sent = false;
    END IF;
END $$;
