import { Hono } from 'hono'
import { requireIdentity } from '../middleware/auth.js'
import { genId } from '../utils/id.js'
import { DB } from '../db.js'

const app = new Hono()

/** 超级管理员判断 */
function isSuperAdmin(c) {
  const identity = c.get('identity') || {}
  return identity.email === '494161546@qq.com' || identity.phone === '13136092523'
}

/**
 * POST /api/users/sync
 * 登录时同步用户（前端登录后调用）
 */
app.post('/sync', async (c) => {
  try {
    const unauth = requireIdentity(c)
    if (unauth) return unauth

    const identity = c.get('identity') || {}
    const { email, phone, loginName } = identity

    // 校验：email 和 phone 不能同时为空
    if (!(email || '').trim() && !(phone || '').trim()) {
      return c.json({ error: 'email 或 phone 至少提供一个' }, 400)
    }

    // 按 email 或 phone 查找已有用户
    let user = null
    if (email) {
      user = await DB.prepare(`SELECT * FROM users WHERE email = ? LIMIT 1`).bind(email).first()
    }
    if (!user && phone) {
      user = await DB.prepare(`SELECT * FROM users WHERE phone = ? LIMIT 1`).bind(phone).first()
    }

    if (user) {
      // 已存在，更新 last_login_at
      await DB.prepare(`UPDATE users SET last_login_at = datetime('now') WHERE id = ?`).bind(user.id).run()
      // 如果 name 有变化也顺带更新
      if (loginName && loginName !== user.name) {
        await DB.prepare(`UPDATE users SET name = ? WHERE id = ?`).bind(loginName, user.id).run()
      }
      const fresh = await DB.prepare(`SELECT * FROM users WHERE id = ?`).bind(user.id).first()
      return c.json({ data: fresh })
    }

    // 不存在，插入新用户
    const userId = genId('user')
    await DB.prepare(
      `INSERT INTO users (id, email, phone, name, role, created_at, last_login_at)
       VALUES (?, ?, ?, ?, 'user', datetime('now'), datetime('now'))`
    ).bind(userId, email || null, phone || null, loginName || null).run()

    const newUser = await DB.prepare(`SELECT * FROM users WHERE id = ?`).bind(userId).first()
    return c.json({ data: newUser }, 201)
  } catch (err) {
    console.error('[users-sync-error]', err)
    return c.json({ error: '同步用户失败', details: err.message }, 500)
  }
})

/**
 * GET /api/users
 * 获取用户列表（仅超级管理员）
 */
app.get('/', async (c) => {
  try {
    const unauth = requireIdentity(c)
    if (unauth) return unauth
    if (!isSuperAdmin(c)) return c.json({ error: '无权限，仅超级管理员可操作' }, 403)

    const q = c.req.query('q') || ''
    const where = ['1=1']
    const args = []

    if (q) {
      where.push('(email LIKE ? OR phone LIKE ? OR name LIKE ?)')
      args.push(`%${q}%`, `%${q}%`, `%${q}%`)
    }

    const { results } = await DB.prepare(
      `SELECT id, email, phone, name, role, created_at, last_login_at
       FROM users
       WHERE ${where.join(' AND ')}
       ORDER BY created_at DESC`
    ).bind(...args).all()

    return c.json({ data: results || [] })
  } catch (err) {
    console.error('[users-list-error]', err)
    return c.json({ error: '获取用户列表失败', details: err.message }, 500)
  }
})

/**
 * PUT /api/users/:id/role
 * 修改用户角色（仅超级管理员）
 */
app.put('/:id/role', async (c) => {
  try {
    const unauth = requireIdentity(c)
    if (unauth) return unauth
    if (!isSuperAdmin(c)) return c.json({ error: '无权限，仅超级管理员可操作' }, 403)

    const id = c.req.param('id')
    const body = await c.req.json().catch(() => ({}))
    const role = body.role

    if (!role || !['user', 'admin'].includes(role)) {
      return c.json({ error: 'role 必须是 user 或 admin' }, 422)
    }

    const user = await DB.prepare(`SELECT * FROM users WHERE id = ?`).bind(id).first()
    if (!user) return c.json({ error: 'not_found' }, 404)

    // 不允许修改超级管理员自己的角色
    if (user.email === '494161546@qq.com' || user.phone === '13136092523') {
      return c.json({ error: '不允许修改超级管理员角色' }, 403)
    }

    await DB.prepare(`UPDATE users SET role = ? WHERE id = ?`).bind(role, id).run()

    c.set('audit', {
      action: 'user.role.update',
      target_id: id,
      meta: { role }
    })

    const fresh = await DB.prepare(`SELECT * FROM users WHERE id = ?`).bind(id).first()
    return c.json({ data: fresh })
  } catch (err) {
    console.error('[users-role-update-error]', err)
    return c.json({ error: '修改用户角色失败', details: err.message }, 500)
  }
})

/**
 * DELETE /api/users/:id
 * 删除用户（仅超级管理员）
 */
app.delete('/:id', async (c) => {
  try {
    const unauth = requireIdentity(c)
    if (unauth) return unauth
    if (!isSuperAdmin(c)) return c.json({ error: '无权限，仅超级管理员可操作' }, 403)

    const id = c.req.param('id')
    const user = await DB.prepare(`SELECT * FROM users WHERE id = ?`).bind(id).first()
    if (!user) return c.json({ error: 'not_found' }, 404)

    // 不允许删除超级管理员自己
    if (user.email === '494161546@qq.com' || user.phone === '13136092523') {
      return c.json({ error: '不允许删除超级管理员' }, 403)
    }

    await DB.prepare(`DELETE FROM users WHERE id = ?`).bind(id).run()

    c.set('audit', {
      action: 'user.delete',
      target_id: id,
      meta: { email: user.email, phone: user.phone, name: user.name }
    })

    return c.json({ ok: true })
  } catch (err) {
    console.error('[users-delete-error]', err)
    return c.json({ error: '删除用户失败', details: err.message }, 500)
  }
})

export default app
