CREATE TABLE org_divisions (
    id BIGSERIAL PRIMARY KEY,
    code VARCHAR(64) NOT NULL,
    name VARCHAR(255) NOT NULL,
    sort_order INT NOT NULL DEFAULT 0,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE UNIQUE INDEX idx_org_divisions_code_ci ON org_divisions (LOWER(TRIM(code)));

CREATE TRIGGER tr_org_divisions_updated
    BEFORE UPDATE ON org_divisions
    FOR EACH ROW EXECUTE FUNCTION workpulse_set_updated_at();

CREATE INDEX idx_org_divisions_active_sort ON org_divisions (is_active, sort_order);
