-- 为已有学校补齐学校级默认实训任务；不会覆盖任何学校管理员已保存的默认配置。
START TRANSACTION;

CREATE TABLE IF NOT EXISTS school_default_task_initialization (
  school_id varchar(64) NOT NULL,
  status varchar(16) NOT NULL,
  last_error varchar(1000) NULL,
  attempt_count int NOT NULL DEFAULT 0,
  create_time datetime NOT NULL,
  update_time datetime NOT NULL,
  PRIMARY KEY (school_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='学校默认实训任务初始化状态';

INSERT INTO task_allocation (id, class_id, school_id, module, disabled_status, sort)
SELECT UUID(), CONCAT('SCHOOL_DEFAULT:', s.school_id), s.school_id, p.module, p.disabled_status, p.sort
FROM school s
JOIN task_allocation p ON p.class_id = '999999999'
WHERE s.school_id <> '999999999'
  AND NOT EXISTS (
    SELECT 1
    FROM task_allocation existing_task
    WHERE existing_task.class_id = CONCAT('SCHOOL_DEFAULT:', s.school_id)
  );

INSERT INTO school_default_task_initialization (
  school_id, status, last_error, attempt_count, create_time, update_time
)
SELECT s.school_id, 'READY', NULL, 1, NOW(), NOW()
FROM school s
WHERE s.school_id <> '999999999'
  AND EXISTS (
    SELECT 1
    FROM task_allocation default_task
    WHERE default_task.class_id = CONCAT('SCHOOL_DEFAULT:', s.school_id)
  )
ON DUPLICATE KEY UPDATE
  status = IF(status = 'READY', status, 'READY'),
  update_time = NOW();

COMMIT;

SELECT school_id, status, attempt_count, update_time
FROM school_default_task_initialization
ORDER BY update_time DESC;
