-- ═══════════════════════════════════════════════════════════
-- Fix: 发货单(biz_delivery_order) rfq_id 非空约束修复
--
-- 问题描述:
--   client 类型发货单不关联 RFQ(询价单)，rfq_id 应为 NULL
--   若表存在 NOT NULL 约束，会导致 SQLIntegrityConstraintViolationException
--
-- 修复:
--   1) 确保 rfq_id 列允许 NULL
--   2) 补充缺失的 DDL（该表在项目中无建表脚本）
-- ═══════════════════════════════════════════════════════════

SET NAMES utf8mb4;

-- 1. 检查并移除 rfq_id 上的 NOT NULL 约束
--    (MySQL 中通过 MODIFY COLUMN 去掉 NOT NULL)
DROP PROCEDURE IF EXISTS fix_rfq_nullable;
DELIMITER //
CREATE PROCEDURE fix_rfq_nullable()
BEGIN
  DECLARE col_is_nullable VARCHAR(3);
  SELECT IS_NULLABLE INTO col_is_nullable
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'biz_delivery_order'
    AND COLUMN_NAME = 'rfq_id';

  IF col_is_nullable = 'NO' THEN
    ALTER TABLE biz_delivery_order MODIFY COLUMN rfq_id BIGINT DEFAULT NULL COMMENT '关联RFQ ID(client类型可为空)';
    SELECT 'rfq_id 已从 NOT NULL 改为 NULL' AS info;
  ELSE
    SELECT 'rfq_id 已经是可空状态' AS info;
  END IF;
END //
DELIMITER ;
CALL fix_rfq_nullable();
DROP PROCEDURE IF EXISTS fix_rfq_nullable;

-- 2. 同理确保 supplier_id 允许 NULL（client 类型没有供应商）
DROP PROCEDURE IF EXISTS fix_supplier_nullable;
DELIMITER //
CREATE PROCEDURE fix_supplier_nullable()
BEGIN
  DECLARE col_is_nullable VARCHAR(3);
  SELECT IS_NULLABLE INTO col_is_nullable
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'biz_delivery_order'
    AND COLUMN_NAME = 'supplier_id';

  IF col_is_nullable = 'NO' THEN
    ALTER TABLE biz_delivery_order MODIFY COLUMN supplier_id BIGINT DEFAULT NULL COMMENT '供应商ID(client类型可为空)';
    SELECT 'supplier_id 已从 NOT NULL 改为 NULL' AS info;
  ELSE
    SELECT 'supplier_id 已经是可空状态' AS info;
  END IF;
END //
DELIMITER ;
CALL fix_supplier_nullable();
DROP PROCEDURE IF EXISTS fix_supplier_nullable;

-- 3. 验证结果
SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_TYPE, COLUMN_COMMENT
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
  AND TABLE_NAME = 'biz_delivery_order'
  AND COLUMN_NAME IN ('rfq_id', 'supplier_id', 'quotation_id', 'client_quote_id');

SELECT '修复完成' AS result;
