-- Migration: 041-add-clients-updated-at.sql
-- Description: Add updated_at column to clients table (missing from migration 036)
-- Date: 2026-06-21
-- Root cause: migration 036 created clients table without updated_at, but a
--             BEFORE UPDATE trigger update_clients_updated_at references it.

-- ─────────────────────────────────────────────────────────────
-- 1. Add missing updated_at column
-- ─────────────────────────────────────────────────────────────
ALTER TABLE clients ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();

-- ─────────────────────────────────────────────────────────────
-- 2. Update trigger function to handle clients (it may already exist,
--    but ensure it can handle the updated_at column)
-- ─────────────────────────────────────────────────────────────
-- The trigger function update_updated_at_column() already exists from
-- migration 001. We just need to ensure the column exists, which step 1 does.

-- ─────────────────────────────────────────────────────────────
-- 3. Sync trigger (drop + recreate) to guarantee it picks up the column
-- ─────────────────────────────────────────────────────────────
DROP TRIGGER IF EXISTS update_clients_updated_at ON clients;
CREATE TRIGGER update_clients_updated_at
    BEFORE UPDATE ON clients
    FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();

COMMENT ON COLUMN clients.updated_at IS 'Auto-updated on every row change';
