-- V1: 조직 / 인사 (직급, 조직, 설계사, 이력)

CREATE TABLE grade (
    grade_id    SERIAL PRIMARY KEY,
    grade_name  VARCHAR(50)  NOT NULL,
    grade_level INT          NOT NULL,
    grade_group VARCHAR(20),
    description VARCHAR(200),
    is_active   CHAR(1)      NOT NULL DEFAULT 'Y',
    sort_order  INT          NOT NULL DEFAULT 0
);
COMMENT ON TABLE grade IS '직급';

CREATE TABLE organization (
    org_id          SERIAL PRIMARY KEY,
    parent_org_id   BIGINT REFERENCES organization(org_id),
    org_name        VARCHAR(100) NOT NULL,
    org_type        VARCHAR(10)  NOT NULL,           -- HQ / BR / TM
    org_level       INT          NOT NULL,
    region          VARCHAR(50),
    effective_from  DATE         NOT NULL,
    effective_to    DATE,
    is_active       CHAR(1)      NOT NULL DEFAULT 'Y',
    created_at      TIMESTAMP    NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMP,
    created_by      BIGINT
);
COMMENT ON TABLE organization IS '조직';
CREATE INDEX idx_org_parent ON organization(parent_org_id);
CREATE INDEX idx_org_type   ON organization(org_type, is_active);

CREATE TABLE agent (
    agent_id      SERIAL PRIMARY KEY,
    org_id        BIGINT       NOT NULL REFERENCES organization(org_id),
    grade_id      BIGINT       NOT NULL REFERENCES grade(grade_id),
    agent_name    VARCHAR(50)  NOT NULL,
    resident_no   VARCHAR(200),                      -- AES 암호화
    license_no    VARCHAR(50),
    phone         VARCHAR(20),
    email         VARCHAR(100),
    bank_code     VARCHAR(10),
    account_no    VARCHAR(200),                      -- AES 암호화
    status        VARCHAR(10)  NOT NULL DEFAULT 'ACTIVE',  -- ACTIVE / LEAVE / SUSPEND
    join_date     DATE,
    leave_date    DATE,
    created_at    TIMESTAMP    NOT NULL DEFAULT NOW(),
    updated_at    TIMESTAMP
);
COMMENT ON TABLE agent IS '설계사';
CREATE INDEX idx_agent_org    ON agent(org_id, status);
CREATE INDEX idx_agent_lic    ON agent(license_no);
CREATE INDEX idx_agent_status ON agent(status);

CREATE TABLE agent_org_history (
    history_id     SERIAL PRIMARY KEY,
    agent_id       BIGINT NOT NULL REFERENCES agent(agent_id),
    from_org_id    BIGINT,
    to_org_id      BIGINT,
    from_grade_id  BIGINT,
    to_grade_id    BIGINT,
    change_type    VARCHAR(20) NOT NULL,             -- TRANSFER / PROMOTE / DEMOTE / JOIN / LEAVE
    change_date    DATE        NOT NULL,
    change_reason  VARCHAR(200),
    created_at     TIMESTAMP   NOT NULL DEFAULT NOW(),
    created_by     BIGINT
);
CREATE INDEX idx_aoh_agent ON agent_org_history(agent_id, change_date);
