-- V45: 위촉계약 (agent_contract)
--      보험사-설계사 간 위촉계약서. 보험사별 활동 자격 + 위촉수수료 관리.

CREATE TABLE agent_contract (
    contract_id          BIGSERIAL    PRIMARY KEY,
    agent_id             BIGINT       NOT NULL REFERENCES agent(agent_id),
    carrier_id           BIGINT       NOT NULL REFERENCES insurance_company(company_id),
    contract_no          VARCHAR(50)  NOT NULL,
    signed_date          DATE         NOT NULL,
    effective_from       DATE         NOT NULL,
    effective_to         DATE,
    status               VARCHAR(20)  NOT NULL DEFAULT 'ACTIVE',
    onboarding_bonus_amount NUMERIC(15,2) NOT NULL DEFAULT 0,
    -- 위촉수수료 (입사 인센티브 성격)
    terminated_at        TIMESTAMP,
    terminated_reason    VARCHAR(500),
    created_at           TIMESTAMP    NOT NULL DEFAULT NOW(),
    created_by           BIGINT,
    updated_at           TIMESTAMP,
    updated_by           BIGINT,
    UNIQUE (agent_id, carrier_id, contract_no),
    CHECK (status IN ('ACTIVE','TERMINATED','SUSPENDED'))
);

COMMENT ON TABLE  agent_contract                         IS '위촉계약 — 보험사-설계사 위촉계약서 + 효력 기간 + 위촉수수료';
COMMENT ON COLUMN agent_contract.agent_id               IS '설계사 FK';
COMMENT ON COLUMN agent_contract.carrier_id             IS '보험사 FK (insurance_company)';
COMMENT ON COLUMN agent_contract.contract_no            IS '위촉계약 번호';
COMMENT ON COLUMN agent_contract.signed_date            IS '위촉계약 서명일';
COMMENT ON COLUMN agent_contract.effective_from         IS '위촉 효력 시작일';
COMMENT ON COLUMN agent_contract.effective_to           IS '위촉 효력 종료일 (NULL=현재 유효)';
COMMENT ON COLUMN agent_contract.status                 IS 'ACTIVE=유효/TERMINATED=해촉/SUSPENDED=정지';
COMMENT ON COLUMN agent_contract.onboarding_bonus_amount IS '위촉수수료 (위촉 시 지급하는 인센티브)';
COMMENT ON COLUMN agent_contract.terminated_reason      IS '해촉 사유';

CREATE INDEX idx_ac_agent         ON agent_contract(agent_id, status);
CREATE INDEX idx_ac_carrier       ON agent_contract(carrier_id, status);
CREATE INDEX idx_ac_effective     ON agent_contract(effective_from, effective_to);
