-- 创建目标子任务表
CREATE TABLE IF NOT EXISTS `t_goal_tasks` (
  `id` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '任务ID',
  `goal_id` CHAR(36) NOT NULL COMMENT '目标ID',
  `user_id` VARCHAR(255) NOT NULL COMMENT '用户ID',
  `title` VARCHAR(255) NOT NULL COMMENT '任务标题',
  `description` TEXT COMMENT '任务描述',
  `start_date` DATE NOT NULL COMMENT '任务开始日期',
  `end_date` DATE NOT NULL COMMENT '任务结束日期',
  `target_count` INT NOT NULL DEFAULT 1 COMMENT '任务目标次数（如喝水8次）',
  `current_count` INT NOT NULL DEFAULT 0 COMMENT '任务当前完成次数',
  `status` ENUM('pending', 'in_progress', 'completed', 'overdue', 'skipped') NOT NULL DEFAULT 'pending' COMMENT '任务状态',
  `progress_percentage` INT NOT NULL DEFAULT 0 COMMENT '完成进度百分比 (0-100)',
  `completed_at` DATETIME COMMENT '任务完成时间',
  `notes` TEXT COMMENT '任务备注',
  `metadata` JSON COMMENT '任务额外数据',
  `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` BOOLEAN NOT NULL DEFAULT FALSE COMMENT '是否删除',
  PRIMARY KEY (`id`),
  INDEX `idx_goal_id` (`goal_id`),
  INDEX `idx_user_id` (`user_id`),
  INDEX `idx_status` (`status`),
  INDEX `idx_start_date` (`start_date`),
  INDEX `idx_end_date` (`end_date`),
  INDEX `idx_deleted` (`deleted`),
  INDEX `idx_user_goal` (`user_id`, `goal_id`),
  INDEX `idx_user_status` (`user_id`, `status`),
  INDEX `idx_user_date_range` (`user_id`, `start_date`, `end_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='目标子任务表';

-- 添加外键约束
ALTER TABLE `t_goal_tasks` 
ADD CONSTRAINT `fk_goal_tasks_goal_id` 
FOREIGN KEY (`goal_id`) REFERENCES `t_goals` (`id`) 
ON DELETE CASCADE ON UPDATE CASCADE;

-- 添加检查约束（MySQL 8.0+）
-- ALTER TABLE `t_goal_tasks` 
-- ADD CONSTRAINT `chk_target_count_positive` CHECK (`target_count` > 0);
-- 
-- ALTER TABLE `t_goal_tasks` 
-- ADD CONSTRAINT `chk_current_count_non_negative` CHECK (`current_count` >= 0);
-- 
-- ALTER TABLE `t_goal_tasks` 
-- ADD CONSTRAINT `chk_progress_percentage_range` CHECK (`progress_percentage` >= 0 AND `progress_percentage` <= 100);
-- 
-- ALTER TABLE `t_goal_tasks` 
-- ADD CONSTRAINT `chk_date_range` CHECK (`end_date` >= `start_date`);
