-- Clarify the managed flow_config effect contract used by AI generation.
-- Idempotent: publish a new version only when the current prompt does not
-- already explain update_related.relationField.

DELIMITER $$

DROP PROCEDURE IF EXISTS upgrade_flow_relation_field_prompt_20260715$$

CREATE PROCEDURE upgrade_flow_relation_field_prompt_20260715()
BEGIN
    DECLARE v_template_id BIGINT;
    DECLARE v_current_version_id BIGINT;
    DECLARE v_new_version_id BIGINT;
    DECLARE v_version_no INT;
    DECLARE v_version_label VARCHAR(50);
    DECLARE v_generate_type VARCHAR(50);
    DECLARE v_prompt_code VARCHAR(100);
    DECLARE v_system_prompt LONGTEXT;
    DECLARE v_user_prompt_contract VARCHAR(255);
    DECLARE v_user_prompt_template LONGTEXT;
    DECLARE v_target_prompt LONGTEXT;
    DECLARE v_provider_code VARCHAR(50);
    DECLARE v_model VARCHAR(100);
    DECLARE v_pipeline_release_code VARCHAR(100);
    DECLARE v_content_hash CHAR(64);
    DECLARE v_old_rule TEXT;
    DECLARE v_new_rule TEXT;

    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        ROLLBACK;
        RESIGNAL;
    END;

    START TRANSACTION;

    SELECT t.prompt_template_id, t.current_version_id, t.generate_type, t.prompt_code,
           v.system_prompt, v.user_prompt_contract, v.user_prompt_template,
           v.provider_code, v.model, v.pipeline_release_code
      INTO v_template_id, v_current_version_id, v_generate_type, v_prompt_code,
           v_system_prompt, v_user_prompt_contract, v_user_prompt_template,
           v_provider_code, v_model, v_pipeline_release_code
      FROM factory_prompt_template t
      JOIN factory_prompt_version v ON v.prompt_version_id = t.current_version_id
     WHERE t.prompt_code = 'front.flow_config'
     FOR UPDATE;

    SET v_old_rule = '6. decrease/increase 必须给 table、relationField、field、amount；decrease 还要给 min。';
    SET v_new_rule = '6. decrease、increase、update_related 必须给 table 和 relationField；relationField 是 ownerTable 上保存目标表主键的字段。update_related 更新当前记录自身（effect.table 等于 ownerTable）时，relationField 必须填写 ownerTable 主键请求字段，通常为 id。decrease/increase 还必须给 field、amount，decrease 还要给 min；只有 create_record 可以省略 relationField。';

    IF LOCATE('只有 create_record 可以省略 relationField', v_system_prompt) = 0 THEN
        IF LOCATE(v_old_rule, v_system_prompt) > 0 THEN
            SET v_target_prompt = REPLACE(v_system_prompt, v_old_rule, v_new_rule);
        ELSE
            SET v_target_prompt = CONCAT(v_system_prompt, CHAR(10), v_new_rule);
        END IF;

        SELECT COALESCE(MAX(version_no), 0) + 1
          INTO v_version_no
          FROM factory_prompt_version
         WHERE prompt_template_id = v_template_id
         FOR UPDATE;
        SET v_version_label = CONCAT('V', v_version_no);
        SET v_content_hash = SHA2(CONCAT(
                '{"generateType":', JSON_QUOTE(v_generate_type),
                ',"promptCode":', JSON_QUOTE(v_prompt_code),
                ',"systemPrompt":', JSON_QUOTE(v_target_prompt),
                ',"userPromptContract":', JSON_QUOTE(v_user_prompt_contract),
                ',"userPromptTemplate":', JSON_QUOTE(v_user_prompt_template),
                ',"version":', JSON_QUOTE(v_version_label), '}'), 256);

        INSERT INTO factory_prompt_version
            (prompt_template_id, version_no, version_label, system_prompt,
             user_prompt_contract, user_prompt_template, provider_code, model,
             content_hash, status, parent_version_id, pipeline_release_code,
             published_by, published_at, create_by, create_time, remark)
        VALUES
            (v_template_id, v_version_no, v_version_label, v_target_prompt,
             v_user_prompt_contract, v_user_prompt_template, v_provider_code, v_model,
             v_content_hash, 'DRAFT', v_current_version_id, v_pipeline_release_code,
             '', NULL, 'system-upgrade', NOW(),
             'Require relationField for update_related effects');
        SET v_new_version_id = LAST_INSERT_ID();

        UPDATE factory_prompt_version
           SET status = 'RETIRED'
         WHERE prompt_template_id = v_template_id
           AND status = 'PUBLISHED'
           AND prompt_version_id <> v_new_version_id;
        UPDATE factory_prompt_version
           SET status = 'PUBLISHED', published_by = 'system-upgrade', published_at = NOW()
         WHERE prompt_version_id = v_new_version_id AND status = 'DRAFT';
        UPDATE factory_prompt_template
           SET current_version_id = v_new_version_id,
               update_by = 'system-upgrade', update_time = NOW()
         WHERE prompt_template_id = v_template_id;
    END IF;

    COMMIT;
END$$

CALL upgrade_flow_relation_field_prompt_20260715()$$
DROP PROCEDURE upgrade_flow_relation_field_prompt_20260715$$

DELIMITER ;
