-- 保质期提醒小程序 - 数据库初始化脚本
-- 执行前请确保已创建数据库并选择正确的数据库

-- ============================================
-- 1. 物品表 (expiry_items)
-- ============================================
CREATE TABLE IF NOT EXISTS expiry_items (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
  user_id BIGINT UNSIGNED NOT NULL COMMENT '用户ID（关联 users 表）',
  mini_program_id BIGINT UNSIGNED NOT NULL COMMENT '小程序ID（关联 mini_programs 表）',
  name VARCHAR(100) NOT NULL COMMENT '物品名称',
  category VARCHAR(20) NOT NULL COMMENT '分类：food/medicine/cosmetic/other',
  production_date DATE DEFAULT NULL COMMENT '生产日期（可选）',
  expiry_date DATE NOT NULL COMMENT '过期日期',
  shelf_life_days INT DEFAULT NULL COMMENT '保质期天数（可选）',
  quantity INT DEFAULT 1 COMMENT '数量',
  location VARCHAR(50) DEFAULT NULL COMMENT '存放位置（可选）',
  remark VARCHAR(255) DEFAULT NULL COMMENT '备注（可选）',
  status VARCHAR(20) DEFAULT 'normal' COMMENT '状态：normal/used/discarded（expiring/expired 由业务动态计算）',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  deleted_at TIMESTAMP NULL DEFAULT NULL COMMENT '软删除时间',
  CONSTRAINT chk_expiry_category CHECK (category IN ('food', 'medicine', 'cosmetic', 'other')),
  CONSTRAINT chk_expiry_quantity CHECK (quantity > 0),
  CONSTRAINT chk_expiry_status CHECK (status IN ('normal', 'used', 'discarded')),
  
  -- 索引
  INDEX idx_user_expiry (user_id, expiry_date) COMMENT '用户+过期日期索引（最常用查询）',
  INDEX idx_user_category (user_id, category) COMMENT '用户+分类索引',
  INDEX idx_user_status (user_id, status) COMMENT '用户+状态索引',
  INDEX idx_deleted_at (deleted_at) COMMENT '软删除索引'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='保质期物品表';

-- ============================================
-- 2. 用户设置表 (expiry_user_settings)
-- ============================================
CREATE TABLE IF NOT EXISTS expiry_user_settings (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY COMMENT '主键ID',
  user_id BIGINT UNSIGNED NOT NULL UNIQUE COMMENT '用户ID（唯一）',
  remind_days JSON DEFAULT (JSON_ARRAY(7,3,1)) COMMENT '提醒天数数组，例如 [7,3,1]',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  
  -- 索引
  INDEX idx_user_id (user_id) COMMENT '用户ID索引'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='保质期用户设置表';

-- ============================================
-- 3. 插入测试数据（可选）
-- ============================================
-- 注意：以下测试数据需要根据实际的 user_id 和 mini_program_id 调整

-- 示例：假设 user_id=1, mini_program_id=1
-- INSERT INTO expiry_items (user_id, mini_program_id, name, category, production_date, expiry_date, shelf_life_days, quantity, location, remark) VALUES
-- (1, 1, '伊利纯牛奶', 'food', '2026-02-01', '2026-03-10', 37, 6, '冰箱', ''),
-- (1, 1, '感冒灵颗粒', 'medicine', NULL, '2027-12-31', NULL, 1, '药箱', ''),
-- (1, 1, '雅诗兰黛面霜', 'cosmetic', '2025-06-01', '2028-06-01', 1095, 1, '梳妆台', '');

-- 插入默认用户设置
-- INSERT INTO expiry_user_settings (user_id, remind_days) VALUES
-- (1, '[7,3,1]');

-- ============================================
-- 4. 验证表结构
-- ============================================
-- 查看表结构
-- SHOW CREATE TABLE expiry_items;
-- SHOW CREATE TABLE expiry_user_settings;

-- 查看索引
-- SHOW INDEX FROM expiry_items;
-- SHOW INDEX FROM expiry_user_settings;

-- ============================================
-- 5. 常用查询示例
-- ============================================

-- 查询用户的所有物品
-- SELECT * FROM expiry_items WHERE user_id = 1 AND deleted_at IS NULL;

-- 查询即将过期的物品（7天内）
-- SELECT * FROM expiry_items 
-- WHERE user_id = 1 
--   AND deleted_at IS NULL
--   AND expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY)
-- ORDER BY expiry_date ASC;

-- 查询已过期的物品
-- SELECT * FROM expiry_items 
-- WHERE user_id = 1 
--   AND deleted_at IS NULL
--   AND expiry_date < CURDATE()
-- ORDER BY expiry_date DESC;

-- 统计汇总
-- SELECT 
--   COUNT(*) as total_items,
--   SUM(CASE WHEN expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) as expiring_soon,
--   SUM(CASE WHEN expiry_date < CURDATE() THEN 1 ELSE 0 END) as expired,
--   SUM(CASE WHEN expiry_date > DATE_ADD(CURDATE(), INTERVAL 7 DAY) THEN 1 ELSE 0 END) as normal
-- FROM expiry_items 
-- WHERE user_id = 1 
--   AND deleted_at IS NULL
--   AND status NOT IN ('used', 'discarded');

-- ============================================
-- 6. 数据清理（谨慎使用）
-- ============================================

-- 物理删除已软删除超过30天的记录
-- DELETE FROM expiry_items 
-- WHERE deleted_at IS NOT NULL 
--   AND deleted_at < DATE_SUB(NOW(), INTERVAL 30 DAY);

-- 清空测试数据（谨慎使用！）
-- TRUNCATE TABLE expiry_items;
-- TRUNCATE TABLE expiry_user_settings;

-- ============================================
-- 7. 性能优化建议
-- ============================================

-- 定期分析表，优化查询性能
-- ANALYZE TABLE expiry_items;
-- ANALYZE TABLE expiry_user_settings;

-- 查看表状态
-- SHOW TABLE STATUS LIKE 'expiry_%';

-- ============================================
-- 初始化完成
-- ============================================
