const express = require('express');
const router = express.Router();
const { get, run, all } = require('../utils/db');
const { success, fail } = require('../utils/response');
const { authUser } = require('../middleware/auth');

router.use(authUser);

// 地址列表
router.get('/list', (req, res) => {
  try {
    const list = all('SELECT * FROM user_addresses WHERE user_id=? ORDER BY is_default DESC, id DESC', [req.userId]);
    return res.json(success(list));
  } catch (e) {
    return res.json(fail('获取地址失败'));
  }
});

// 保存地址（新增或更新）
router.post('/save', (req, res) => {
  try {
    const { id, name, phone, province, city, district, detail, zip_code, is_default } = req.body;
    if (!name || !phone) return res.json(fail('请填写完整信息'));

    if (id) {
      // 更新
      const addr = get('SELECT id FROM user_addresses WHERE id=? AND user_id=?', [id, req.userId]);
      if (!addr) return res.json(fail('地址不存在'));
      if (is_default) run('UPDATE user_addresses SET is_default=0 WHERE user_id=?', [req.userId]);
      run(`UPDATE user_addresses SET name=?,phone=?,province=?,city=?,district=?,detail=?,zip_code=?,is_default=?
        WHERE id=? AND user_id=?`,
        [name, phone, province||'', city||'', district||'', detail||'', zip_code||'', is_default?1:0, id, req.userId]);
      return res.json(success(null, '更新成功'));
    } else {
      // 新增
      if (is_default) run('UPDATE user_addresses SET is_default=0 WHERE user_id=?', [req.userId]);
      const count = get('SELECT COUNT(*) as c FROM user_addresses WHERE user_id=?', [req.userId]);
      const def = is_default || count.c === 0 ? 1 : 0;
      const r = run(
        'INSERT INTO user_addresses(user_id,name,phone,province,city,district,detail,zip_code,is_default) VALUES(?,?,?,?,?,?,?,?,?)',
        [req.userId, name, phone, province||'', city||'', district||'', detail||'', zip_code||'', def]
      );
      return res.json(success({ id: r.lastInsertRowid }, '新增成功'));
    }
  } catch (e) {
    return res.json(fail('保存失败'));
  }
});

// 设为默认地址
router.post('/:id/default', (req, res) => {
  try {
    const addr = get('SELECT id FROM user_addresses WHERE id=? AND user_id=?', [req.params.id, req.userId]);
    if (!addr) return res.json(fail('地址不存在'));
    run('UPDATE user_addresses SET is_default=0 WHERE user_id=?', [req.userId]);
    run('UPDATE user_addresses SET is_default=1 WHERE id=?', [req.params.id]);
    return res.json(success(null, '设置成功'));
  } catch (e) {
    return res.json(fail('设置失败'));
  }
});

// 删除地址
router.delete('/:id', (req, res) => {
  try {
    run('DELETE FROM user_addresses WHERE id=? AND user_id=?', [req.params.id, req.userId]);
    return res.json(success(null, '删除成功'));
  } catch (e) {
    return res.json(fail('删除失败'));
  }
});

module.exports = router;
