CREATE TABLE IF NOT EXISTS teams (
    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 UNIQUE,
    active     BOOLEAN     NOT NULL
);

CREATE TABLE IF NOT EXISTS team_default_roles (
    team_id BIGINT      NOT NULL REFERENCES teams (id) ON DELETE CASCADE,
    role    VARCHAR(20) NOT NULL,
    PRIMARY KEY (team_id, role)
);

ALTER TABLE users ADD COLUMN IF NOT EXISTS team_id BIGINT REFERENCES teams (id);

INSERT INTO teams (created_at, updated_at, code, name, active)
VALUES
    (now(), now(), 'ITOPS', 'IT운영팀', TRUE),
    (now(), now(), 'DEV1', '개발1팀', TRUE),
    (now(), now(), 'SEC', '보안팀', TRUE)
ON CONFLICT (code) DO UPDATE
SET name = EXCLUDED.name,
    active = EXCLUDED.active,
    updated_at = now();

INSERT INTO team_default_roles (team_id, role)
SELECT id, 'ADMIN' FROM teams WHERE code = 'ITOPS'
ON CONFLICT DO NOTHING;
INSERT INTO team_default_roles (team_id, role)
SELECT id, 'HOST' FROM teams WHERE code = 'DEV1'
ON CONFLICT DO NOTHING;
INSERT INTO team_default_roles (team_id, role)
SELECT id, 'SECURITY' FROM teams WHERE code = 'SEC'
ON CONFLICT DO NOTHING;

UPDATE users SET team_id = (SELECT id FROM teams WHERE code = 'ITOPS'), department = 'IT운영팀'
WHERE username IN ('admin', 'a') AND team_id IS NULL;
UPDATE users SET team_id = (SELECT id FROM teams WHERE code = 'DEV1'), department = '개발1팀'
WHERE username IN ('host', 'h') AND team_id IS NULL;
UPDATE users SET team_id = (SELECT id FROM teams WHERE code = 'SEC'), department = '보안팀'
WHERE username IN ('security', 's') AND team_id IS NULL;
