-- V46: 설계사 자격 관리 (agent_license)
--      생보/손보/변액 자격증 만료·갱신 이력. 만료 임박 알림용 인덱스 포함.

CREATE TABLE agent_license (
    license_id     BIGSERIAL    PRIMARY KEY,
    agent_id       BIGINT       NOT NULL REFERENCES agent(agent_id),
    license_type   VARCHAR(20)  NOT NULL,
    license_no     VARCHAR(50)  NOT NULL,
    issued_date    DATE         NOT NULL,
    expires_date   DATE         NOT NULL,
    renewed_from   BIGINT       REFERENCES agent_license(license_id),
    -- 갱신 전 자격증 참조
    status         VARCHAR(20)  NOT NULL DEFAULT 'ACTIVE',
    created_at     TIMESTAMP    NOT NULL DEFAULT NOW(),
    created_by     BIGINT,
    updated_at     TIMESTAMP,
    UNIQUE (agent_id, license_type, license_no),
    CHECK (license_type IN ('LIFE','NONLIFE','VARIABLE')),
    CHECK (status IN ('ACTIVE','EXPIRED','SUSPENDED')),
    CHECK (expires_date > issued_date)
);

COMMENT ON TABLE  agent_license              IS '설계사 자격 관리 — 생보/손보/변액 자격증 만료·갱신 이력';
COMMENT ON COLUMN agent_license.agent_id     IS '설계사 FK';
COMMENT ON COLUMN agent_license.license_type IS '자격 종류 (LIFE=생명보험/NONLIFE=손해보험/VARIABLE=변액보험)';
COMMENT ON COLUMN agent_license.license_no   IS '자격증 번호';
COMMENT ON COLUMN agent_license.issued_date  IS '자격증 발급일';
COMMENT ON COLUMN agent_license.expires_date IS '자격증 만료일 (갱신 주기 5년 기준)';
COMMENT ON COLUMN agent_license.renewed_from IS '갱신 전 자격증 ID (갱신 이력 추적용)';
COMMENT ON COLUMN agent_license.status       IS 'ACTIVE=유효/EXPIRED=만료/SUSPENDED=정지';

-- 만료 임박 알림용 인덱스 (expires_date 단독 + 복합)
CREATE INDEX idx_al_agent        ON agent_license(agent_id, status);
CREATE INDEX idx_al_expires      ON agent_license(expires_date, status);
CREATE INDEX idx_al_type_expires ON agent_license(license_type, expires_date);
