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

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

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

CREATE INDEX IF NOT EXISTS idx_departments_is_active
    ON departments (is_active);
