const express = require('express');
const db = require('../config/database');
const { authenticate } = require('../middleware/auth');
const { asyncHandler, AppError } = require('../middleware/errorHandler');
const { validateRecurringPayload, normalizeNote } = require('../utils/validators');

const router = express.Router();

// 获取周期性账单
router.get('/', authenticate, asyncHandler(async (req, res) => {
  const stmt = db.prepare('SELECT * FROM recurring_bills WHERE user_id = ? ORDER BY day ASC');
  const bills = stmt.all(req.userId);
  res.json(bills);
}));

// 新增周期性账单
router.post('/', authenticate, asyncHandler(async (req, res) => {
  const { type, amount, category, day, note } = req.body;

  const validationError = validateRecurringPayload(req.body);
  if (validationError) {
    throw new AppError(validationError, 400, 'VALIDATION_ERROR');
  }

  const stmt = db.prepare(`
    INSERT INTO recurring_bills (user_id, type, amount, category, day, note)
    VALUES (?, ?, ?, ?, ?, ?)
  `);

  const result = stmt.run(req.userId, type, amount, category.trim(), day, normalizeNote(note));
  console.log(`Recurring bill created: user=${req.userId}, id=${result.lastInsertRowid}`);

  res.json({ id: result.lastInsertRowid, message: '添加成功' });
}));

// 更新周期性账单
router.put('/:id', authenticate, asyncHandler(async (req, res) => {
  const { id } = req.params;
  const { type, amount, category, day, note, is_active } = req.body;

  const checkStmt = db.prepare('SELECT * FROM recurring_bills WHERE id = ? AND user_id = ?');
  const bill = checkStmt.get(id, req.userId);

  if (!bill) {
    throw new AppError('账单不存在', 404, 'NOT_FOUND');
  }

  const validationError = validateRecurringPayload(req.body);
  if (validationError) {
    throw new AppError(validationError, 400, 'VALIDATION_ERROR');
  }

  const stmt = db.prepare(`
    UPDATE recurring_bills SET type = ?, amount = ?, category = ?, day = ?, note = ?, is_active = ?
    WHERE id = ? AND user_id = ?
  `);

  stmt.run(type, amount, category.trim(), day, normalizeNote(note), is_active !== undefined ? is_active : 1, id, req.userId);
  console.log(`Recurring bill updated: user=${req.userId}, id=${id}`);

  res.json({ message: '更新成功' });
}));

// 删除周期性账单
router.delete('/:id', authenticate, asyncHandler(async (req, res) => {
  const { id } = req.params;

  const checkStmt = db.prepare('SELECT * FROM recurring_bills WHERE id = ? AND user_id = ?');
  const bill = checkStmt.get(id, req.userId);

  if (!bill) {
    throw new AppError('账单不存在', 404, 'NOT_FOUND');
  }

  const stmt = db.prepare('DELETE FROM recurring_bills WHERE id = ? AND user_id = ?');
  stmt.run(id, req.userId);
  console.log(`Recurring bill deleted: user=${req.userId}, id=${id}`);

  res.json({ message: '删除成功' });
}));

// 应用周期性账单
router.post('/:id/apply', authenticate, asyncHandler(async (req, res) => {
  const { id } = req.params;

  const checkStmt = db.prepare('SELECT * FROM recurring_bills WHERE id = ? AND user_id = ? AND is_active = 1');
  const bill = checkStmt.get(id, req.userId);

  if (!bill) {
    throw new AppError('账单不存在或已禁用', 404, 'NOT_FOUND');
  }

  // 创建当前日期的账目
  const today = new Date();
  const dateStr = today.toISOString().split('T')[0] + ' ' + today.toTimeString().slice(0, 5);

  const insertStmt = db.prepare(`
    INSERT INTO records (user_id, type, amount, category, date, note)
    VALUES (?, ?, ?, ?, ?, ?)
  `);

  insertStmt.run(req.userId, bill.type, bill.amount, bill.category, dateStr, bill.note || '');
  console.log(`Recurring bill applied: user=${req.userId}, billId=${id}`);

  res.json({ message: '应用成功' });
}));

module.exports = router;
