// ===================================================================
// 售后路由（统一）— ⑥ 订单售后精细化
// 用户端: /api/aftersale/*
// 管理端: /api/admin/aftersale/*
// ===================================================================
const express = require('express');
const { get, all } = require('../utils/db');
const { success, fail, page } = require('../utils/response');
const { authUser, authAdmin } = require('../middleware/auth');
const { demoSafeGuard } = require('./admin-auth');
const aftersale = require('../lib/aftersale');

const userRouter = express.Router();
const adminRouter = express.Router();

// ---------- 用户端 ----------
// 申请售后（自动判定仅退款/退货退款）
userRouter.post('/apply', authUser, async (req, res) => {
  try {
    const r = aftersale.applyRefund({
      order_id: req.body.order_id,
      userId: req.userId,
      reason: req.body.reason,
      images: req.body.images ? JSON.stringify(req.body.images) : '[]',
      amount: req.body.amount,
    });
    return r.ok ? res.json(success(r, '申请成功')) : res.json(fail(r.reason));
  } catch (e) { return res.json(fail('申请失败: ' + e.message)); }
});

// 我只 cancel（待审核）
userRouter.post('/:id/cancel', authUser, (req, res) => {
  try {
    const r = aftersale.cancelRefund(req.params.id, req.userId);
    return r.ok ? res.json(success(null, '已取消')) : res.json(fail(r.reason));
  } catch (e) { return res.json(fail('取消失败: ' + e.message)); }
});

// 退货退款：填写退货物流
userRouter.post('/:id/return', authUser, (req, res) => {
  try {
    const r = aftersale.submitReturn(req.params.id, req.userId, {
      shipping_company: req.body.shipping_company,
      shipping_no: req.body.shipping_no,
    });
    return r.ok ? res.json(success(null, '已提交退货物流')) : res.json(fail(r.reason));
  } catch (e) { return res.json(fail('提交失败: ' + e.message)); }
});

// 我的售后列表
userRouter.get('/my', authUser, (req, res) => {
  try {
    const { page: p = 1, pageSize = 10 } = req.query;
    const pageNum = Math.max(1, +p);
    const size = Math.min(50, Math.max(1, +pageSize));
    const total = get('SELECT COUNT(*) c FROM refunds WHERE user_id=?', [req.userId]).c;
    const list = all(
      `SELECT r.*, o.order_no FROM refunds r
       LEFT JOIN orders o ON r.order_id=o.id
       WHERE r.user_id=? ORDER BY r.id DESC LIMIT ? OFFSET ?`,
      [req.userId, size, (pageNum - 1) * size]
    );
    list.forEach(x => { x.type_label = aftersale.TYPE_LABEL[x.type] || x.type; x.status_label = aftersale.STATUS_LABEL[x.status] || x.status; });
    return res.json(page(list, total, pageNum, size));
  } catch (e) { return res.json(fail('查询失败')); }
});

// 售后详情（用户）
userRouter.get('/:id', authUser, (req, res) => {
  try {
    const row = get('SELECT * FROM refunds WHERE id=? AND user_id=?', [req.params.id, req.userId]);
    if (!row) return res.json(fail('售后单不存在'));
    row.type_label = aftersale.TYPE_LABEL[row.type] || row.type;
    row.status_label = aftersale.STATUS_LABEL[row.status] || row.status;
    return res.json(success(row));
  } catch (e) { return res.json(fail('查询失败')); }
});

// ---------- 管理端 ----------
// 售后列表（可按状态/类型筛选）
adminRouter.get('/list', authAdmin, (req, res) => {
  try {
    const { page: p = 1, pageSize = 20, status, type, keyword } = req.query;
    const pageNum = Math.max(1, +p);
    const size = Math.min(100, Math.max(1, +pageSize));
    let where = 'WHERE 1=1';
    const params = [];
    if (status) { where += ' AND r.status=?'; params.push(status); }
    if (type) { where += ' AND r.type=?'; params.push(type); }
    if (keyword) { where += ' AND (r.refund_no LIKE ? OR o.order_no LIKE ?)'; params.push(`%${keyword}%`, `%${keyword}%`); }
    const total = get(`SELECT COUNT(*) c FROM refunds r LEFT JOIN orders o ON r.order_id=o.id ${where}`, params).c;
    const list = all(
      `SELECT r.*, o.order_no, u.nickname as user_name FROM refunds r
       LEFT JOIN orders o ON r.order_id=o.id
       LEFT JOIN users u ON r.user_id=u.id ${where} ORDER BY r.id DESC LIMIT ? OFFSET ?`,
      [...params, size, (pageNum - 1) * size]
    );
    list.forEach(x => { x.type_label = aftersale.TYPE_LABEL[x.type] || x.type; x.status_label = aftersale.STATUS_LABEL[x.status] || x.status; });
    return res.json(page(list, total, pageNum, size));
  } catch (e) { return res.json(fail('查询失败')); }
});

// 审核：同意（仅退款→退款 / 退货退款→待寄回）
adminRouter.post('/:id/approve', authAdmin, demoSafeGuard, async (req, res) => {
  try {
    const r = await aftersale.processRefund(req.params.id, 'approve', req.userId);
    if (!r.ok) return res.json(fail(r.reason));
    if (r.status === 'awaiting_return') return res.json(success({ status: r.status }, '已同意，等待用户寄回'));
    return res.json(success({ status: r.status }, '退款已通过'));
  } catch (e) { return res.json(fail('操作失败: ' + e.message)); }
});

// 确认收货并退款（退货退款最终节点）
adminRouter.post('/:id/confirm-return', authAdmin, demoSafeGuard, async (req, res) => {
  try {
    const r = await aftersale.completeRefund(req.params.id, req.userId);
    return r.ok ? res.json(success({ status: r.status }, '已确认收货并退款')) : res.json(fail(r.reason));
  } catch (e) { return res.json(fail('操作失败: ' + e.message)); }
});

// 审核：驳回
adminRouter.post('/:id/reject', authAdmin, demoSafeGuard, async (req, res) => {
  try {
    const r = await aftersale.processRefund(req.params.id, 'reject', req.userId, { reject_reason: req.body.reject_reason });
    return r.ok ? res.json(success(null, '已驳回')) : res.json(fail(r.reason));
  } catch (e) { return res.json(fail('操作失败: ' + e.message)); }
});

// 售后枚举（管理端下拉用）
adminRouter.get('/meta', authAdmin, (req, res) => {
  res.json(success({
    types: Object.keys(aftersale.TYPE).map(k => ({ value: aftersale.TYPE[k], label: aftersale.TYPE_LABEL[aftersale.TYPE[k]] })),
    statuses: Object.keys(aftersale.STATUS).map(k => ({ value: aftersale.STATUS[k], label: aftersale.STATUS_LABEL[aftersale.STATUS[k]] })),
  }));
});

module.exports = { userRouter, adminRouter };
