import { Router } from "express";
import { z } from "zod";
import { prisma } from "@stamp/shared";
import { signToken } from "../lib/jwt.js";
import { requireAuth } from "../middleware/auth.js";

const router = Router();

const phoneRegex = /^1[3-9]\d{9}$/;

const registerSchema = z.object({
  username: z.string().min(1, "用户名不能为空").max(20, "用户名最长 20 字符"),
  phone: z.string().regex(phoneRegex, "手机号格式不正确"),
});

const loginSchema = z.object({
  phone: z.string().regex(phoneRegex, "手机号格式不正确"),
});

router.post("/register", async (req, res) => {
  const parsed = registerSchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ success: false, error: { code: "VALIDATION", message: parsed.error.issues[0].message } });
    return;
  }
  const { username, phone } = parsed.data;

  const existing = await prisma.user.findFirst({
    where: { OR: [{ username }, { phone }] },
  });
  if (existing) {
    const field = existing.username === username ? "用户名" : "手机号";
    res.status(409).json({ success: false, error: { code: "DUPLICATE", message: `该${field}已被注册` } });
    return;
  }

  const user = await prisma.user.create({ data: { username, phone } });
  const token = signToken(user.id);
  res.json({ success: true, data: { user: { id: user.id, username: user.username, phone: user.phone }, token } });
});

router.post("/login", async (req, res) => {
  const parsed = loginSchema.safeParse(req.body);
  if (!parsed.success) {
    res.status(400).json({ success: false, error: { code: "VALIDATION", message: parsed.error.issues[0].message } });
    return;
  }
  const user = await prisma.user.findUnique({ where: { phone: parsed.data.phone } });
  if (!user) {
    res.status(404).json({ success: false, error: { code: "NOT_FOUND", message: "该手机号未注册" } });
    return;
  }
  const token = signToken(user.id);
  res.json({ success: true, data: { user: { id: user.id, username: user.username, phone: user.phone }, token } });
});

router.get("/me", requireAuth, async (req, res) => {
  const user = await prisma.user.findUnique({ where: { id: req.userId } });
  if (!user) {
    res.status(404).json({ success: false, error: { code: "NOT_FOUND", message: "用户不存在" } });
    return;
  }
  res.json({ success: true, data: { id: user.id, username: user.username, phone: user.phone } });
});

export default router;
