SET @schema_name := DATABASE();

SET @agent_creator_relation_table_exists := (
    SELECT COUNT(1)
    FROM information_schema.tables
    WHERE table_schema = @schema_name
      AND table_name = 'agent_creator_relation'
);

SET @create_agent_creator_relation_table_sql := IF(
    @agent_creator_relation_table_exists = 0,
    'CREATE TABLE agent_creator_relation (
        id BIGINT NOT NULL AUTO_INCREMENT COMMENT ''PK'',
        agent_id BIGINT NOT NULL COMMENT ''에이전트 회원 ID (member.id 참조)'',
        creator_id BIGINT NOT NULL COMMENT ''크리에이터 회원 ID (member.id 참조)'',
        assigned_at TIMESTAMP NOT NULL COMMENT ''소속 시작 시각'',
        unassigned_at TIMESTAMP NULL DEFAULT NULL COMMENT ''소속 종료 시각(NULL이면 현재 활성 소속)'',
        active_creator_key TINYINT GENERATED ALWAYS AS (
            CASE
                WHEN unassigned_at IS NULL THEN 1
                ELSE NULL
            END
        ) STORED,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''생성 시각'',
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''수정 시각'',
        PRIMARY KEY (id),
        UNIQUE KEY uk_agent_creator_relation_creator_active (creator_id, active_creator_key),
        KEY idx_agent_creator_relation_agent_id (agent_id),
        KEY idx_agent_creator_relation_creator_id (creator_id),
        KEY idx_agent_creator_relation_agent_unassigned_at (agent_id, unassigned_at),
        KEY idx_agent_creator_relation_creator_assigned_at (creator_id, assigned_at),
        KEY idx_agent_creator_relation_creator_unassigned_at (creator_id, unassigned_at),
        CONSTRAINT fk_agent_creator_relation_agent_id FOREIGN KEY (agent_id) REFERENCES member (id),
        CONSTRAINT fk_agent_creator_relation_creator_id FOREIGN KEY (creator_id) REFERENCES member (id),
        CONSTRAINT chk_agent_creator_relation_period CHECK (unassigned_at IS NULL OR assigned_at < unassigned_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT=''에이전트-크리에이터 소속 관계''',
    'SELECT ''agent_creator_relation already exists'' AS message'
);

PREPARE create_agent_creator_relation_table_stmt FROM @create_agent_creator_relation_table_sql;
EXECUTE create_agent_creator_relation_table_stmt;
DEALLOCATE PREPARE create_agent_creator_relation_table_stmt;

SET @agent_creator_relation_has_assigned_at := (
    SELECT COUNT(1)
    FROM information_schema.columns
    WHERE table_schema = @schema_name
      AND table_name = 'agent_creator_relation'
      AND column_name = 'assigned_at'
);

SET @alter_agent_creator_relation_add_assigned_at_sql := IF(
    @agent_creator_relation_table_exists = 1 AND @agent_creator_relation_has_assigned_at = 0,
    'ALTER TABLE agent_creator_relation ADD COLUMN assigned_at TIMESTAMP NOT NULL COMMENT ''소속 시작 시각'' AFTER creator_id',
    'SELECT ''agent_creator_relation.assigned_at already exists'' AS message'
);

PREPARE alter_agent_creator_relation_add_assigned_at_stmt FROM @alter_agent_creator_relation_add_assigned_at_sql;
EXECUTE alter_agent_creator_relation_add_assigned_at_stmt;
DEALLOCATE PREPARE alter_agent_creator_relation_add_assigned_at_stmt;

SET @agent_creator_relation_has_unassigned_at := (
    SELECT COUNT(1)
    FROM information_schema.columns
    WHERE table_schema = @schema_name
      AND table_name = 'agent_creator_relation'
      AND column_name = 'unassigned_at'
);

SET @alter_agent_creator_relation_add_unassigned_at_sql := IF(
    @agent_creator_relation_table_exists = 1 AND @agent_creator_relation_has_unassigned_at = 0,
    'ALTER TABLE agent_creator_relation ADD COLUMN unassigned_at TIMESTAMP NULL DEFAULT NULL COMMENT ''소속 종료 시각(NULL이면 현재 활성 소속)'' AFTER assigned_at',
    'SELECT ''agent_creator_relation.unassigned_at already exists'' AS message'
);

PREPARE alter_agent_creator_relation_add_unassigned_at_stmt FROM @alter_agent_creator_relation_add_unassigned_at_sql;
EXECUTE alter_agent_creator_relation_add_unassigned_at_stmt;
DEALLOCATE PREPARE alter_agent_creator_relation_add_unassigned_at_stmt;

SET @agent_creator_relation_has_active_creator_key := (
    SELECT COUNT(1)
    FROM information_schema.columns
    WHERE table_schema = @schema_name
      AND table_name = 'agent_creator_relation'
      AND column_name = 'active_creator_key'
);

SET @alter_agent_creator_relation_add_active_creator_key_sql := IF(
    @agent_creator_relation_table_exists = 1 AND @agent_creator_relation_has_active_creator_key = 0,
    'ALTER TABLE agent_creator_relation ADD COLUMN active_creator_key TINYINT GENERATED ALWAYS AS (CASE WHEN unassigned_at IS NULL THEN 1 ELSE NULL END) STORED AFTER unassigned_at',
    'SELECT ''agent_creator_relation.active_creator_key already exists'' AS message'
);

PREPARE alter_agent_creator_relation_add_active_creator_key_stmt FROM @alter_agent_creator_relation_add_active_creator_key_sql;
EXECUTE alter_agent_creator_relation_add_active_creator_key_stmt;
DEALLOCATE PREPARE alter_agent_creator_relation_add_active_creator_key_stmt;

SET @agent_creator_relation_creator_unique_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_creator_relation'
      AND index_name = 'uk_agent_creator_relation_creator_id'
);

SET @drop_agent_creator_relation_creator_unique_sql := IF(
    @agent_creator_relation_creator_unique_exists > 0,
    'ALTER TABLE agent_creator_relation DROP INDEX uk_agent_creator_relation_creator_id',
    'SELECT ''uk_agent_creator_relation_creator_id already dropped'' AS message'
);

PREPARE drop_agent_creator_relation_creator_unique_stmt FROM @drop_agent_creator_relation_creator_unique_sql;
EXECUTE drop_agent_creator_relation_creator_unique_stmt;
DEALLOCATE PREPARE drop_agent_creator_relation_creator_unique_stmt;

SET @agent_creator_relation_creator_active_unique_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_creator_relation'
      AND index_name = 'uk_agent_creator_relation_creator_active'
);

SET @add_agent_creator_relation_creator_active_unique_sql := IF(
    @agent_creator_relation_table_exists = 1 AND @agent_creator_relation_creator_active_unique_exists = 0,
    'ALTER TABLE agent_creator_relation ADD UNIQUE INDEX uk_agent_creator_relation_creator_active (creator_id, active_creator_key)',
    'SELECT ''uk_agent_creator_relation_creator_active already exists'' AS message'
);

PREPARE add_agent_creator_relation_creator_active_unique_stmt FROM @add_agent_creator_relation_creator_active_unique_sql;
EXECUTE add_agent_creator_relation_creator_active_unique_stmt;
DEALLOCATE PREPARE add_agent_creator_relation_creator_active_unique_stmt;

SET @agent_creator_relation_period_check_exists := (
    SELECT COUNT(1)
    FROM information_schema.table_constraints
    WHERE table_schema = @schema_name
      AND table_name = 'agent_creator_relation'
      AND constraint_name = 'chk_agent_creator_relation_period'
      AND constraint_type = 'CHECK'
);

SET @add_agent_creator_relation_period_check_sql := IF(
    @agent_creator_relation_table_exists = 1 AND @agent_creator_relation_period_check_exists = 0,
    'ALTER TABLE agent_creator_relation ADD CONSTRAINT chk_agent_creator_relation_period CHECK (unassigned_at IS NULL OR assigned_at < unassigned_at)',
    'SELECT ''chk_agent_creator_relation_period already exists'' AS message'
);

PREPARE add_agent_creator_relation_period_check_stmt FROM @add_agent_creator_relation_period_check_sql;
EXECUTE add_agent_creator_relation_period_check_stmt;
DEALLOCATE PREPARE add_agent_creator_relation_period_check_stmt;

SET @agent_creator_relation_agent_unassigned_index_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_creator_relation'
      AND index_name = 'idx_agent_creator_relation_agent_unassigned_at'
);

SET @add_agent_creator_relation_agent_unassigned_index_sql := IF(
    @agent_creator_relation_table_exists = 1 AND @agent_creator_relation_agent_unassigned_index_exists = 0,
    'ALTER TABLE agent_creator_relation ADD INDEX idx_agent_creator_relation_agent_unassigned_at (agent_id, unassigned_at)',
    'SELECT ''idx_agent_creator_relation_agent_unassigned_at already exists'' AS message'
);

PREPARE add_agent_creator_relation_agent_unassigned_index_stmt FROM @add_agent_creator_relation_agent_unassigned_index_sql;
EXECUTE add_agent_creator_relation_agent_unassigned_index_stmt;
DEALLOCATE PREPARE add_agent_creator_relation_agent_unassigned_index_stmt;

SET @agent_creator_relation_creator_assigned_index_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_creator_relation'
      AND index_name = 'idx_agent_creator_relation_creator_assigned_at'
);

SET @add_agent_creator_relation_creator_assigned_index_sql := IF(
    @agent_creator_relation_table_exists = 1 AND @agent_creator_relation_creator_assigned_index_exists = 0,
    'ALTER TABLE agent_creator_relation ADD INDEX idx_agent_creator_relation_creator_assigned_at (creator_id, assigned_at)',
    'SELECT ''idx_agent_creator_relation_creator_assigned_at already exists'' AS message'
);

PREPARE add_agent_creator_relation_creator_assigned_index_stmt FROM @add_agent_creator_relation_creator_assigned_index_sql;
EXECUTE add_agent_creator_relation_creator_assigned_index_stmt;
DEALLOCATE PREPARE add_agent_creator_relation_creator_assigned_index_stmt;

SET @agent_creator_relation_creator_unassigned_index_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_creator_relation'
      AND index_name = 'idx_agent_creator_relation_creator_unassigned_at'
);

SET @add_agent_creator_relation_creator_unassigned_index_sql := IF(
    @agent_creator_relation_table_exists = 1 AND @agent_creator_relation_creator_unassigned_index_exists = 0,
    'ALTER TABLE agent_creator_relation ADD INDEX idx_agent_creator_relation_creator_unassigned_at (creator_id, unassigned_at)',
    'SELECT ''idx_agent_creator_relation_creator_unassigned_at already exists'' AS message'
);

PREPARE add_agent_creator_relation_creator_unassigned_index_stmt FROM @add_agent_creator_relation_creator_unassigned_index_sql;
EXECUTE add_agent_creator_relation_creator_unassigned_index_stmt;
DEALLOCATE PREPARE add_agent_creator_relation_creator_unassigned_index_stmt;

SET @agent_settlement_ratio_table_exists := (
    SELECT COUNT(1)
    FROM information_schema.tables
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_ratio'
);

SET @create_agent_settlement_ratio_table_sql := IF(
    @agent_settlement_ratio_table_exists = 0,
    'CREATE TABLE agent_settlement_ratio (
        id BIGINT NOT NULL AUTO_INCREMENT COMMENT ''PK'',
        member_id BIGINT NOT NULL COMMENT ''에이전트 회원 ID (member.id 참조)'',
        settlement_ratio INT NOT NULL COMMENT ''에이전트 정산 비율(%)'',
        effective_from TIMESTAMP NOT NULL COMMENT ''비율 시작 시각'',
        effective_to TIMESTAMP NULL DEFAULT NULL COMMENT ''비율 종료 시각(NULL이면 현재 활성 비율)'',
        active_ratio_key TINYINT GENERATED ALWAYS AS (
            CASE
                WHEN effective_to IS NULL THEN 1
                ELSE NULL
            END
        ) STORED,
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''생성 시각'',
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''수정 시각'',
        PRIMARY KEY (id),
        UNIQUE KEY uk_agent_settlement_ratio_member_active (member_id, active_ratio_key),
        KEY idx_agent_settlement_ratio_member_effective_to (member_id, effective_to),
        KEY idx_agent_settlement_ratio_member_effective_from (member_id, effective_from),
        CONSTRAINT fk_agent_settlement_ratio_member_id FOREIGN KEY (member_id) REFERENCES member (id),
        CONSTRAINT chk_agent_settlement_ratio_period CHECK (effective_to IS NULL OR effective_from < effective_to)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT=''에이전트 정산 비율''',
    'SELECT ''agent_settlement_ratio already exists'' AS message'
);

PREPARE create_agent_settlement_ratio_table_stmt FROM @create_agent_settlement_ratio_table_sql;
EXECUTE create_agent_settlement_ratio_table_stmt;
DEALLOCATE PREPARE create_agent_settlement_ratio_table_stmt;

SET @agent_settlement_ratio_has_effective_from := (
    SELECT COUNT(1)
    FROM information_schema.columns
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_ratio'
      AND column_name = 'effective_from'
);

SET @alter_agent_settlement_ratio_add_effective_from_sql := IF(
    @agent_settlement_ratio_table_exists = 1 AND @agent_settlement_ratio_has_effective_from = 0,
    'ALTER TABLE agent_settlement_ratio ADD COLUMN effective_from TIMESTAMP NOT NULL COMMENT ''비율 시작 시각'' AFTER settlement_ratio',
    'SELECT ''agent_settlement_ratio.effective_from already exists'' AS message'
);

PREPARE alter_agent_settlement_ratio_add_effective_from_stmt FROM @alter_agent_settlement_ratio_add_effective_from_sql;
EXECUTE alter_agent_settlement_ratio_add_effective_from_stmt;
DEALLOCATE PREPARE alter_agent_settlement_ratio_add_effective_from_stmt;

SET @agent_settlement_ratio_has_effective_to := (
    SELECT COUNT(1)
    FROM information_schema.columns
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_ratio'
      AND column_name = 'effective_to'
);

SET @alter_agent_settlement_ratio_add_effective_to_sql := IF(
    @agent_settlement_ratio_table_exists = 1 AND @agent_settlement_ratio_has_effective_to = 0,
    'ALTER TABLE agent_settlement_ratio ADD COLUMN effective_to TIMESTAMP NULL DEFAULT NULL COMMENT ''비율 종료 시각(NULL이면 현재 활성 비율)'' AFTER effective_from',
    'SELECT ''agent_settlement_ratio.effective_to already exists'' AS message'
);

PREPARE alter_agent_settlement_ratio_add_effective_to_stmt FROM @alter_agent_settlement_ratio_add_effective_to_sql;
EXECUTE alter_agent_settlement_ratio_add_effective_to_stmt;
DEALLOCATE PREPARE alter_agent_settlement_ratio_add_effective_to_stmt;

SET @agent_settlement_ratio_has_active_ratio_key := (
    SELECT COUNT(1)
    FROM information_schema.columns
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_ratio'
      AND column_name = 'active_ratio_key'
);

SET @alter_agent_settlement_ratio_add_active_ratio_key_sql := IF(
    @agent_settlement_ratio_table_exists = 1 AND @agent_settlement_ratio_has_active_ratio_key = 0,
    'ALTER TABLE agent_settlement_ratio ADD COLUMN active_ratio_key TINYINT GENERATED ALWAYS AS (CASE WHEN effective_to IS NULL THEN 1 ELSE NULL END) STORED AFTER effective_to',
    'SELECT ''agent_settlement_ratio.active_ratio_key already exists'' AS message'
);

PREPARE alter_agent_settlement_ratio_add_active_ratio_key_stmt FROM @alter_agent_settlement_ratio_add_active_ratio_key_sql;
EXECUTE alter_agent_settlement_ratio_add_active_ratio_key_stmt;
DEALLOCATE PREPARE alter_agent_settlement_ratio_add_active_ratio_key_stmt;

SET @agent_settlement_ratio_member_unique_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_ratio'
      AND index_name = 'uk_agent_settlement_ratio_member_id'
);

SET @drop_agent_settlement_ratio_member_unique_sql := IF(
    @agent_settlement_ratio_member_unique_exists > 0,
    'ALTER TABLE agent_settlement_ratio DROP INDEX uk_agent_settlement_ratio_member_id',
    'SELECT ''uk_agent_settlement_ratio_member_id already dropped'' AS message'
);

PREPARE drop_agent_settlement_ratio_member_unique_stmt FROM @drop_agent_settlement_ratio_member_unique_sql;
EXECUTE drop_agent_settlement_ratio_member_unique_stmt;
DEALLOCATE PREPARE drop_agent_settlement_ratio_member_unique_stmt;

SET @agent_settlement_ratio_member_active_unique_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_ratio'
      AND index_name = 'uk_agent_settlement_ratio_member_active'
);

SET @add_agent_settlement_ratio_member_active_unique_sql := IF(
    @agent_settlement_ratio_table_exists = 1 AND @agent_settlement_ratio_member_active_unique_exists = 0,
    'ALTER TABLE agent_settlement_ratio ADD UNIQUE INDEX uk_agent_settlement_ratio_member_active (member_id, active_ratio_key)',
    'SELECT ''uk_agent_settlement_ratio_member_active already exists'' AS message'
);

PREPARE add_agent_settlement_ratio_member_active_unique_stmt FROM @add_agent_settlement_ratio_member_active_unique_sql;
EXECUTE add_agent_settlement_ratio_member_active_unique_stmt;
DEALLOCATE PREPARE add_agent_settlement_ratio_member_active_unique_stmt;

SET @agent_settlement_ratio_has_deleted_at := (
    SELECT COUNT(1)
    FROM information_schema.columns
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_ratio'
      AND column_name = 'deleted_at'
);

SET @drop_agent_settlement_ratio_deleted_at_sql := IF(
    @agent_settlement_ratio_table_exists = 1 AND @agent_settlement_ratio_has_deleted_at > 0,
    'ALTER TABLE agent_settlement_ratio DROP COLUMN deleted_at',
    'SELECT ''agent_settlement_ratio.deleted_at already dropped'' AS message'
);

PREPARE drop_agent_settlement_ratio_deleted_at_stmt FROM @drop_agent_settlement_ratio_deleted_at_sql;
EXECUTE drop_agent_settlement_ratio_deleted_at_stmt;
DEALLOCATE PREPARE drop_agent_settlement_ratio_deleted_at_stmt;

SET @agent_settlement_ratio_period_check_exists := (
    SELECT COUNT(1)
    FROM information_schema.table_constraints
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_ratio'
      AND constraint_name = 'chk_agent_settlement_ratio_period'
      AND constraint_type = 'CHECK'
);

SET @add_agent_settlement_ratio_period_check_sql := IF(
    @agent_settlement_ratio_table_exists = 1 AND @agent_settlement_ratio_period_check_exists = 0,
    'ALTER TABLE agent_settlement_ratio ADD CONSTRAINT chk_agent_settlement_ratio_period CHECK (effective_to IS NULL OR effective_from < effective_to)',
    'SELECT ''chk_agent_settlement_ratio_period already exists'' AS message'
);

PREPARE add_agent_settlement_ratio_period_check_stmt FROM @add_agent_settlement_ratio_period_check_sql;
EXECUTE add_agent_settlement_ratio_period_check_stmt;
DEALLOCATE PREPARE add_agent_settlement_ratio_period_check_stmt;

SET @agent_settlement_ratio_member_effective_to_index_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_ratio'
      AND index_name = 'idx_agent_settlement_ratio_member_effective_to'
);

SET @add_agent_settlement_ratio_member_effective_to_index_sql := IF(
    @agent_settlement_ratio_table_exists = 1 AND @agent_settlement_ratio_member_effective_to_index_exists = 0,
    'ALTER TABLE agent_settlement_ratio ADD INDEX idx_agent_settlement_ratio_member_effective_to (member_id, effective_to)',
    'SELECT ''idx_agent_settlement_ratio_member_effective_to already exists'' AS message'
);

PREPARE add_agent_settlement_ratio_member_effective_to_index_stmt FROM @add_agent_settlement_ratio_member_effective_to_index_sql;
EXECUTE add_agent_settlement_ratio_member_effective_to_index_stmt;
DEALLOCATE PREPARE add_agent_settlement_ratio_member_effective_to_index_stmt;

SET @agent_settlement_ratio_member_effective_from_index_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_ratio'
      AND index_name = 'idx_agent_settlement_ratio_member_effective_from'
);

SET @add_agent_settlement_ratio_member_effective_from_index_sql := IF(
    @agent_settlement_ratio_table_exists = 1 AND @agent_settlement_ratio_member_effective_from_index_exists = 0,
    'ALTER TABLE agent_settlement_ratio ADD INDEX idx_agent_settlement_ratio_member_effective_from (member_id, effective_from)',
    'SELECT ''idx_agent_settlement_ratio_member_effective_from already exists'' AS message'
);

PREPARE add_agent_settlement_ratio_member_effective_from_index_stmt FROM @add_agent_settlement_ratio_member_effective_from_index_sql;
EXECUTE add_agent_settlement_ratio_member_effective_from_index_stmt;
DEALLOCATE PREPARE add_agent_settlement_ratio_member_effective_from_index_stmt;

SET @agent_settlement_snapshot_table_exists := (
    SELECT COUNT(1)
    FROM information_schema.tables
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot'
);

SET @create_agent_settlement_snapshot_table_sql := IF(
    @agent_settlement_snapshot_table_exists = 0,
    'CREATE TABLE agent_settlement_snapshot (
        id BIGINT NOT NULL AUTO_INCREMENT COMMENT ''PK'',
        period_start TIMESTAMP NOT NULL COMMENT ''정산 기간 시작 시각'',
        period_end TIMESTAMP NOT NULL COMMENT ''정산 기간 종료 시각'',
        settlement_type VARCHAR(50) NOT NULL COMMENT ''정산 유형(LIVE, CONTENT, COMMUNITY, CHANNEL_DONATION, CONTENT_DONATION)'',
        agent_id BIGINT NOT NULL COMMENT ''에이전트 회원 ID 스냅샷'',
        agent_nickname VARCHAR(255) NOT NULL COMMENT ''에이전트 닉네임 스냅샷'',
        creator_id BIGINT NOT NULL COMMENT ''크리에이터 회원 ID 스냅샷'',
        creator_nickname VARCHAR(255) NOT NULL COMMENT ''크리에이터 닉네임 스냅샷'',
        assignment_id BIGINT NULL COMMENT ''적용된 소속 이력 row ID 스냅샷'',
        agent_settlement_ratio_id BIGINT NULL COMMENT ''적용된 에이전트 정산 비율 이력 row ID 스냅샷'',
        applied_agent_settlement_ratio INT NULL COMMENT ''적용된 에이전트 정산 비율 스냅샷(creator-level summary에 단일 값으로 귀결될 때만 저장)'',
        count INT NOT NULL COMMENT ''건수 스냅샷'',
        total_can INT NOT NULL COMMENT ''총 캔 수 스냅샷'',
        krw INT NOT NULL COMMENT ''원화 금액 스냅샷'',
        fee INT NOT NULL COMMENT ''수수료 스냅샷'',
        settlement_amount INT NOT NULL COMMENT ''크리에이터 세전 정산금 스냅샷'',
        tax INT NOT NULL COMMENT ''원천세/세금 스냅샷'',
        deposit_amount INT NOT NULL COMMENT ''입금액 스냅샷'',
        agent_settlement_amount INT NOT NULL COMMENT ''에이전트 정산금 스냅샷'',
        finalized_at TIMESTAMP NOT NULL COMMENT ''확정 시각'',
        finalized_by_member_id BIGINT NOT NULL COMMENT ''확정한 관리자 회원 ID 스냅샷'',
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''생성 시각'',
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''수정 시각'',
        PRIMARY KEY (id),
        UNIQUE KEY uk_agent_settlement_snapshot_period_type_agent_creator (period_start, period_end, settlement_type, agent_id, creator_id),
        KEY idx_agent_settlement_snapshot_lookup (agent_id, settlement_type, period_start, period_end),
        KEY idx_agent_settlement_snapshot_creator_lookup (creator_id, settlement_type, period_start, period_end),
        KEY idx_agent_settlement_snapshot_assignment_id (assignment_id),
        KEY idx_agent_settlement_snapshot_ratio_id (agent_settlement_ratio_id),
        CONSTRAINT fk_agent_settlement_snapshot_assignment_id FOREIGN KEY (assignment_id) REFERENCES agent_creator_relation (id),
        CONSTRAINT fk_agent_settlement_snapshot_ratio_id FOREIGN KEY (agent_settlement_ratio_id) REFERENCES agent_settlement_ratio (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT=''에이전트 확정 정산 creator-level 스냅샷''',
    'SELECT ''agent_settlement_snapshot already exists'' AS message'
);

PREPARE create_agent_settlement_snapshot_table_stmt FROM @create_agent_settlement_snapshot_table_sql;
EXECUTE create_agent_settlement_snapshot_table_stmt;
DEALLOCATE PREPARE create_agent_settlement_snapshot_table_stmt;

SET @agent_settlement_snapshot_has_assignment_id := (
    SELECT COUNT(1)
    FROM information_schema.columns
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot'
      AND column_name = 'assignment_id'
);

SET @alter_agent_settlement_snapshot_add_assignment_id_sql := IF(
    @agent_settlement_snapshot_table_exists = 1 AND @agent_settlement_snapshot_has_assignment_id = 0,
    'ALTER TABLE agent_settlement_snapshot ADD COLUMN assignment_id BIGINT NULL COMMENT ''적용된 소속 이력 row ID 스냅샷'' AFTER creator_nickname',
    'SELECT ''agent_settlement_snapshot.assignment_id already exists'' AS message'
);

PREPARE alter_agent_settlement_snapshot_add_assignment_id_stmt FROM @alter_agent_settlement_snapshot_add_assignment_id_sql;
EXECUTE alter_agent_settlement_snapshot_add_assignment_id_stmt;
DEALLOCATE PREPARE alter_agent_settlement_snapshot_add_assignment_id_stmt;

SET @agent_settlement_snapshot_has_ratio_id := (
    SELECT COUNT(1)
    FROM information_schema.columns
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot'
      AND column_name = 'agent_settlement_ratio_id'
);

SET @alter_agent_settlement_snapshot_add_ratio_id_sql := IF(
    @agent_settlement_snapshot_table_exists = 1 AND @agent_settlement_snapshot_has_ratio_id = 0,
    'ALTER TABLE agent_settlement_snapshot ADD COLUMN agent_settlement_ratio_id BIGINT NULL COMMENT ''적용된 에이전트 정산 비율 이력 row ID 스냅샷'' AFTER assignment_id',
    'SELECT ''agent_settlement_snapshot.agent_settlement_ratio_id already exists'' AS message'
);

PREPARE alter_agent_settlement_snapshot_add_ratio_id_stmt FROM @alter_agent_settlement_snapshot_add_ratio_id_sql;
EXECUTE alter_agent_settlement_snapshot_add_ratio_id_stmt;
DEALLOCATE PREPARE alter_agent_settlement_snapshot_add_ratio_id_stmt;

SET @agent_settlement_snapshot_unique_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot'
      AND index_name = 'uk_agent_settlement_snapshot_period_type_agent_creator'
);

SET @add_agent_settlement_snapshot_unique_sql := IF(
    @agent_settlement_snapshot_table_exists = 1 AND @agent_settlement_snapshot_unique_exists = 0,
    'ALTER TABLE agent_settlement_snapshot ADD UNIQUE INDEX uk_agent_settlement_snapshot_period_type_agent_creator (period_start, period_end, settlement_type, agent_id, creator_id)',
    'SELECT ''uk_agent_settlement_snapshot_period_type_agent_creator already exists'' AS message'
);

PREPARE add_agent_settlement_snapshot_unique_stmt FROM @add_agent_settlement_snapshot_unique_sql;
EXECUTE add_agent_settlement_snapshot_unique_stmt;
DEALLOCATE PREPARE add_agent_settlement_snapshot_unique_stmt;

SET @agent_settlement_snapshot_lookup_index_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot'
      AND index_name = 'idx_agent_settlement_snapshot_lookup'
);

SET @add_agent_settlement_snapshot_lookup_index_sql := IF(
    @agent_settlement_snapshot_table_exists = 1 AND @agent_settlement_snapshot_lookup_index_exists = 0,
    'ALTER TABLE agent_settlement_snapshot ADD INDEX idx_agent_settlement_snapshot_lookup (agent_id, settlement_type, period_start, period_end)',
    'SELECT ''idx_agent_settlement_snapshot_lookup already exists'' AS message'
);

PREPARE add_agent_settlement_snapshot_lookup_index_stmt FROM @add_agent_settlement_snapshot_lookup_index_sql;
EXECUTE add_agent_settlement_snapshot_lookup_index_stmt;
DEALLOCATE PREPARE add_agent_settlement_snapshot_lookup_index_stmt;

SET @agent_settlement_snapshot_creator_lookup_index_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot'
      AND index_name = 'idx_agent_settlement_snapshot_creator_lookup'
);

SET @add_agent_settlement_snapshot_creator_lookup_index_sql := IF(
    @agent_settlement_snapshot_table_exists = 1 AND @agent_settlement_snapshot_creator_lookup_index_exists = 0,
    'ALTER TABLE agent_settlement_snapshot ADD INDEX idx_agent_settlement_snapshot_creator_lookup (creator_id, settlement_type, period_start, period_end)',
    'SELECT ''idx_agent_settlement_snapshot_creator_lookup already exists'' AS message'
);

PREPARE add_agent_settlement_snapshot_creator_lookup_index_stmt FROM @add_agent_settlement_snapshot_creator_lookup_index_sql;
EXECUTE add_agent_settlement_snapshot_creator_lookup_index_stmt;
DEALLOCATE PREPARE add_agent_settlement_snapshot_creator_lookup_index_stmt;

SET @agent_settlement_snapshot_assignment_index_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot'
      AND index_name = 'idx_agent_settlement_snapshot_assignment_id'
);

SET @add_agent_settlement_snapshot_assignment_index_sql := IF(
    @agent_settlement_snapshot_table_exists = 1 AND @agent_settlement_snapshot_assignment_index_exists = 0,
    'ALTER TABLE agent_settlement_snapshot ADD INDEX idx_agent_settlement_snapshot_assignment_id (assignment_id)',
    'SELECT ''idx_agent_settlement_snapshot_assignment_id already exists'' AS message'
);

PREPARE add_agent_settlement_snapshot_assignment_index_stmt FROM @add_agent_settlement_snapshot_assignment_index_sql;
EXECUTE add_agent_settlement_snapshot_assignment_index_stmt;
DEALLOCATE PREPARE add_agent_settlement_snapshot_assignment_index_stmt;

SET @agent_settlement_snapshot_ratio_index_exists := (
    SELECT COUNT(1)
    FROM information_schema.statistics
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot'
      AND index_name = 'idx_agent_settlement_snapshot_ratio_id'
);

SET @add_agent_settlement_snapshot_ratio_index_sql := IF(
    @agent_settlement_snapshot_table_exists = 1 AND @agent_settlement_snapshot_ratio_index_exists = 0,
    'ALTER TABLE agent_settlement_snapshot ADD INDEX idx_agent_settlement_snapshot_ratio_id (agent_settlement_ratio_id)',
    'SELECT ''idx_agent_settlement_snapshot_ratio_id already exists'' AS message'
);

PREPARE add_agent_settlement_snapshot_ratio_index_stmt FROM @add_agent_settlement_snapshot_ratio_index_sql;
EXECUTE add_agent_settlement_snapshot_ratio_index_stmt;
DEALLOCATE PREPARE add_agent_settlement_snapshot_ratio_index_stmt;

SET @agent_settlement_snapshot_assignment_fk_exists := (
    SELECT COUNT(1)
    FROM information_schema.table_constraints
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot'
      AND constraint_name = 'fk_agent_settlement_snapshot_assignment_id'
      AND constraint_type = 'FOREIGN KEY'
);

SET @add_agent_settlement_snapshot_assignment_fk_sql := IF(
    @agent_settlement_snapshot_table_exists = 1 AND @agent_settlement_snapshot_assignment_fk_exists = 0,
    'ALTER TABLE agent_settlement_snapshot ADD CONSTRAINT fk_agent_settlement_snapshot_assignment_id FOREIGN KEY (assignment_id) REFERENCES agent_creator_relation (id)',
    'SELECT ''fk_agent_settlement_snapshot_assignment_id already exists'' AS message'
);

PREPARE add_agent_settlement_snapshot_assignment_fk_stmt FROM @add_agent_settlement_snapshot_assignment_fk_sql;
EXECUTE add_agent_settlement_snapshot_assignment_fk_stmt;
DEALLOCATE PREPARE add_agent_settlement_snapshot_assignment_fk_stmt;

SET @agent_settlement_snapshot_ratio_fk_exists := (
    SELECT COUNT(1)
    FROM information_schema.table_constraints
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot'
      AND constraint_name = 'fk_agent_settlement_snapshot_ratio_id'
      AND constraint_type = 'FOREIGN KEY'
);

SET @add_agent_settlement_snapshot_ratio_fk_sql := IF(
    @agent_settlement_snapshot_table_exists = 1 AND @agent_settlement_snapshot_ratio_fk_exists = 0,
    'ALTER TABLE agent_settlement_snapshot ADD CONSTRAINT fk_agent_settlement_snapshot_ratio_id FOREIGN KEY (agent_settlement_ratio_id) REFERENCES agent_settlement_ratio (id)',
    'SELECT ''fk_agent_settlement_snapshot_ratio_id already exists'' AS message'
);

PREPARE add_agent_settlement_snapshot_ratio_fk_stmt FROM @add_agent_settlement_snapshot_ratio_fk_sql;
EXECUTE add_agent_settlement_snapshot_ratio_fk_stmt;
DEALLOCATE PREPARE add_agent_settlement_snapshot_ratio_fk_stmt;

SET @agent_settlement_snapshot_source_detail_table_exists := (
    SELECT COUNT(1)
    FROM information_schema.tables
    WHERE table_schema = @schema_name
      AND table_name = 'agent_settlement_snapshot_source_detail'
);

SET @create_agent_settlement_snapshot_source_detail_table_sql := IF(
    @agent_settlement_snapshot_source_detail_table_exists = 0,
    'CREATE TABLE agent_settlement_snapshot_source_detail (
        id BIGINT NOT NULL AUTO_INCREMENT COMMENT ''PK'',
        snapshot_id BIGINT NOT NULL COMMENT ''summary snapshot FK'',
        assignment_id BIGINT NULL COMMENT ''적용된 소속 이력 row ID'',
        agent_settlement_ratio_id BIGINT NULL COMMENT ''적용된 에이전트 정산 비율 이력 row ID'',
        applied_agent_settlement_ratio INT NULL COMMENT ''적용된 에이전트 정산 비율'',
        count INT NOT NULL COMMENT ''source subtotal 건수'',
        total_can INT NOT NULL COMMENT ''source subtotal 총 캔 수'',
        krw INT NOT NULL COMMENT ''source subtotal 원화 금액'',
        fee INT NOT NULL COMMENT ''source subtotal 수수료'',
        settlement_amount INT NOT NULL COMMENT ''source subtotal 크리에이터 세전 정산금'',
        tax INT NOT NULL COMMENT ''source subtotal 세금'',
        deposit_amount INT NOT NULL COMMENT ''source subtotal 입금액'',
        agent_settlement_amount INT NOT NULL COMMENT ''source subtotal 에이전트 정산금'',
        created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''생성 시각'',
        updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''수정 시각'',
        PRIMARY KEY (id),
        KEY idx_agent_settlement_snapshot_source_detail_snapshot_id (snapshot_id),
        KEY idx_agent_settlement_snapshot_source_detail_assignment_id (assignment_id),
        KEY idx_agent_settlement_snapshot_source_detail_ratio_id (agent_settlement_ratio_id),
        CONSTRAINT fk_agent_settlement_snapshot_source_detail_snapshot_id FOREIGN KEY (snapshot_id) REFERENCES agent_settlement_snapshot (id),
        CONSTRAINT fk_agent_settlement_snapshot_source_detail_assignment_id FOREIGN KEY (assignment_id) REFERENCES agent_creator_relation (id),
        CONSTRAINT fk_agent_settlement_snapshot_source_detail_ratio_id FOREIGN KEY (agent_settlement_ratio_id) REFERENCES agent_settlement_ratio (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT=''에이전트 확정 정산 source provenance detail''',
    'SELECT ''agent_settlement_snapshot_source_detail already exists'' AS message'
);

PREPARE create_agent_settlement_snapshot_source_detail_table_stmt FROM @create_agent_settlement_snapshot_source_detail_table_sql;
EXECUTE create_agent_settlement_snapshot_source_detail_table_stmt;
DEALLOCATE PREPARE create_agent_settlement_snapshot_source_detail_table_stmt;
