import { Router } from 'express'
import bcrypt from 'bcrypt'
import { sendSuccess, sendError } from '../middleware/error.js'
import { generateToken } from '../middleware/auth.js'
import adminPool from '../config/admin-pool.js'
import type { AuthUser } from '../types/index.js'

const router = Router()

router.post('/login', async (req, res) => {
  const { username, password } = req.body
  if (!username || !password) {
    return sendError(res, 'Username and password required')
  }

  try {
    const result = await adminPool.query(
      `SELECT tu.id, tu.username, tu.password, tu.role, tu.name, tu.tenant_id,
              tu.store_code, tu.region, tu.dept,
              tc.status as tenant_status
       FROM tenant_users tu
       JOIN tenant_configs tc ON tu.tenant_id = tc.tenant_id
       WHERE tu.username = $1 AND tu.is_active = true`,
      [username]
    )

    if (result.rows.length === 0) {
      return sendError(res, '用户名或密码错误', 401)
    }

    const row = result.rows[0]
    if (row.tenant_status !== 'active') {
      return sendError(res, '租户已停用，请联系平台管理员', 403)
    }

    const valid = await bcrypt.compare(password, row.password)
    if (!valid) {
      return sendError(res, '用户名或密码错误', 401)
    }

    const user: AuthUser = {
      id: String(row.id),
      role: row.role,
      name: row.name,
      tenantId: row.tenant_id,
      storeCode: row.store_code || undefined,
      region: row.region || undefined,
      dept: row.dept || undefined,
    }

    const token = generateToken(user)
    sendSuccess(res, { token, user })
  } catch (err: any) {
    return sendError(res, `登录失败: ${err.message}`)
  }
})

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

export default router
