const express = require('express');
const db = require('../config/database');
const { auth, authorize } = require('../middleware/auth');

const router = express.Router();

router.get('/project/:projectId', auth, (req, res) => {
  const projectId = parseInt(req.params.projectId);

  const permissions = db.prepare(`
    SELECT pp.*, u.username, u.full_name
    FROM project_permissions pp
    JOIN users u ON pp.user_id = u.id
    WHERE pp.project_id = ?
    ORDER BY pp.created_at DESC
  `).all(projectId);

  res.json({ project_permissions: permissions });
});

router.get('/my/:projectId', auth, (req, res) => {
  const projectId = parseInt(req.params.projectId);

  const permission = db.prepare(
    'SELECT * FROM project_permissions WHERE project_id = ? AND user_id = ?'
  ).get(projectId, req.user.id);

  res.json({ permission: permission || null });
});

router.post('/', auth, authorize('admin', 'investment_manager'), (req, res) => {
  const { projectId, userId, canRead, canEdit, canCreate, canDelete } = req.body;

  try {
    const existing = db.prepare(
      'SELECT * FROM project_permissions WHERE project_id = ? AND user_id = ?'
    ).get(projectId, userId);

    if (existing) {
      db.prepare(
        `UPDATE project_permissions
         SET can_read = ?, can_edit = ?, can_create = ?, can_delete = ?
         WHERE project_id = ? AND user_id = ?`
      ).run(canRead !== undefined ? canRead : 1, canEdit !== undefined ? canEdit : 0, canCreate !== undefined ? canCreate : 0, canDelete !== undefined ? canDelete : 0, projectId, userId);

      res.json({ message: '项目权限更新成功' });
    } else {
      const result = db.prepare(
        `INSERT INTO project_permissions (project_id, user_id, can_read, can_edit, can_create, can_delete, created_by)
         VALUES (?, ?, ?, ?, ?, ?, ?)`
      ).run(projectId, userId, canRead !== undefined ? canRead : 1, canEdit !== undefined ? canEdit : 0, canCreate !== undefined ? canCreate : 0, canDelete !== undefined ? canDelete : 0, req.user.id);

      res.status(201).json({ message: '项目权限创建成功', permission_id: result.lastInsertRowid });
    }
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

router.put('/:projectId/:userId', auth, authorize('admin', 'investment_manager'), (req, res) => {
  const { projectId, userId } = req.params;
  const { canRead, canEdit, canCreate, canDelete } = req.body;

  const permission = db.prepare(
    'SELECT * FROM project_permissions WHERE project_id = ? AND user_id = ?'
  ).get(projectId, userId);

  if (!permission) {
    return res.status(404).json({ message: '项目权限不存在' });
  }

  db.prepare(
    `UPDATE project_permissions
     SET can_read = ?, can_edit = ?, can_create = ?, can_delete = ?
     WHERE project_id = ? AND user_id = ?`
  ).run(
    canRead !== undefined ? canRead : permission.can_read,
    canEdit !== undefined ? canEdit : permission.can_edit,
    canCreate !== undefined ? canCreate : permission.can_create,
    canDelete !== undefined ? canDelete : permission.can_delete,
    projectId, userId
  );

  res.json({ message: '项目权限更新成功' });
});

router.delete('/:projectId/:userId', auth, authorize('admin', 'investment_manager'), (req, res) => {
  const { projectId, userId } = req.params;

  db.prepare('DELETE FROM project_permissions WHERE project_id = ? AND user_id = ?').run(projectId, userId);
  res.json({ message: '项目权限已删除' });
});

module.exports = router;
