-- V100: 공동계약 (joint_contract)
--       한 계약을 여러 설계사가 공동 모집 → 지분율(share_rate)로 수수료 배분.
--       공식: 설계사몫 = 계약수수료 × share_rate
--       검증: 계약별 share_rate 합=1 — Service 가드

CREATE TABLE joint_contract (
    joint_id    BIGSERIAL      PRIMARY KEY,
    contract_id INT            NOT NULL REFERENCES contract(contract_id),
    agent_id    INT            NOT NULL REFERENCES agent(agent_id),
    role        VARCHAR(10)    NOT NULL,
    share_rate  NUMERIC(7,4)   NOT NULL,
    created_at  TIMESTAMP      NOT NULL DEFAULT NOW(),
    created_by  BIGINT,
    UNIQUE (contract_id, agent_id),
    CHECK (role IN ('LEAD','SUB')),
    CHECK (share_rate >= 0 AND share_rate <= 1)
);

COMMENT ON TABLE  joint_contract              IS '공동계약 — 복수 설계사의 계약별 지분율 관리';
COMMENT ON COLUMN joint_contract.contract_id   IS '대상 계약 FK';
COMMENT ON COLUMN joint_contract.agent_id      IS '참여 설계사 FK';
COMMENT ON COLUMN joint_contract.role          IS '역할 (LEAD=주설계사/SUB=공동설계사)';
COMMENT ON COLUMN joint_contract.share_rate    IS '지분율 (0~1, 계약별 합=1 Service 검증)';

CREATE INDEX idx_jcon_contract ON joint_contract(contract_id);
CREATE INDEX idx_jcon_agent    ON joint_contract(agent_id);
