-- Phase 1.3: Update departments table with new fields
-- Migration: 20260415000003

ALTER TABLE departments ADD COLUMN IF NOT EXISTS code VARCHAR(64);
ALTER TABLE departments ADD COLUMN IF NOT EXISTS description TEXT;
ALTER TABLE departments ADD COLUMN IF NOT EXISTS department_head VARCHAR(255);
ALTER TABLE departments ADD COLUMN IF NOT EXISTS department_email VARCHAR(255);
ALTER TABLE departments ADD COLUMN IF NOT EXISTS visibility VARCHAR(20) DEFAULT 'INTERNAL';
ALTER TABLE departments ADD COLUMN IF NOT EXISTS transfers_enabled BOOLEAN DEFAULT false;
ALTER TABLE departments ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW();

UPDATE departments SET updated_at = COALESCE(updated_at, created_at, NOW()) WHERE updated_at IS NULL;

CREATE UNIQUE INDEX IF NOT EXISTS idx_departments_code ON departments(LOWER(code)) WHERE code IS NOT NULL;
CREATE INDEX IF NOT EXISTS idx_departments_is_active ON departments(is_active);
