CREATE TABLE IF NOT EXISTS purpose_codes (
    id             BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    created_at     TIMESTAMP   NOT NULL DEFAULT now(),
    updated_at     TIMESTAMP   NOT NULL DEFAULT now(),
    code           VARCHAR(40) NOT NULL UNIQUE,
    name           VARCHAR(80) NOT NULL,
    sort_order     INTEGER     NOT NULL,
    active         BOOLEAN     NOT NULL,
    custom_allowed BOOLEAN     NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_purpose_code_active_sort ON purpose_codes (active, sort_order);

CREATE TABLE IF NOT EXISTS system_settings (
    id            BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    created_at    TIMESTAMP   NOT NULL DEFAULT now(),
    updated_at    TIMESTAMP   NOT NULL DEFAULT now(),
    setting_key   VARCHAR(80) NOT NULL UNIQUE,
    setting_value VARCHAR(255)
);

ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS work_name VARCHAR(255);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS control_name VARCHAR(80);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS control_team VARCHAR(80);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS control_contact VARCHAR(60);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS watcher1_name VARCHAR(80);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS watcher1_team VARCHAR(80);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS watcher1_contact VARCHAR(60);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS watcher2_name VARCHAR(80);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS watcher2_team VARCHAR(80);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS watcher2_contact VARCHAR(60);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS purpose_code VARCHAR(40);
ALTER TABLE visit_requests ADD COLUMN IF NOT EXISTS purpose_detail VARCHAR(255);

INSERT INTO purpose_codes (created_at, updated_at, code, name, sort_order, active, custom_allowed)
VALUES
    (now(), now(), 'WORK', '작업', 10, TRUE, FALSE),
    (now(), now(), 'INSPECTION', '점검', 20, TRUE, FALSE),
    (now(), now(), 'DELIVERY', '납품', 30, TRUE, FALSE),
    (now(), now(), 'MEETING', '회의', 40, TRUE, FALSE),
    (now(), now(), 'VISIT', '방문', 50, TRUE, FALSE),
    (now(), now(), 'ETC', '기타', 100, TRUE, TRUE)
ON CONFLICT (code) DO NOTHING;

INSERT INTO system_settings (created_at, updated_at, setting_key, setting_value)
VALUES
    (now(), now(), 'watcher1.name', '류관순'),
    (now(), now(), 'watcher1.team', 'IT전략국'),
    (now(), now(), 'watcher1.contact', '313')
ON CONFLICT (setting_key) DO NOTHING;
