import { Router } from 'express'
import { query } from '../config/database.js'
import { sendSuccess, sendError } from '../middleware/error.js'
import { generateToken } from '../middleware/auth.js'
import type { AuthUser } from '../types/index.js'

const router = Router()

const mockUsers: AuthUser[] = [
  { id: '1', role: 'hq', name: '总部管理员' },
  { id: '2', role: 'regional', name: '区域经理', region: '北京' },
  { id: '3', role: 'store', name: '潘家园店长', storeCode: '0026' },
  { id: '4', role: 'dept', name: '商品部', dept: 'product' },
]

router.post('/login', async (req, res) => {
  const { username, password } = req.body
  if (!username || !password) {
    return sendError(res, 'Username and password required')
  }
  const user = mockUsers.find((u) => u.name === username || u.id === username)
  if (!user) {
    return sendError(res, 'Invalid credentials', 401)
  }
  const token = generateToken(user)
  sendSuccess(res, { token, user })
})

router.get('/me', async (req: any, res) => {
  if (!req.user) {
    return sendError(res, 'Not authenticated', 401)
  }
  sendSuccess(res, req.user)
})

export default router
