import { NextResponse } from 'next/server';
import { Role, UserStatus } from '@prisma/client';
import { prisma } from '../../../../lib/prisma';
import { hashPassword } from '../../../../lib/auth';
import { randomToken, addHours } from '../../../../lib/tokens';
import { sendVerificationEmail } from '../../../../lib/mailer';

const APP_URL = process.env.APP_URL || 'http://localhost:3000';

export async function POST(req: Request) {
  try {
    const body = await req.json();
    const email = String(body.email ?? '').trim().toLowerCase();
    const password = String(body.password ?? '');
    const name = body.name ? String(body.name).trim() : null;

    if (!email || !password) {
      return NextResponse.json({ error: 'Email and password are required' }, { status: 400 });
    }
    if (password.length < 8) {
      return NextResponse.json({ error: 'Password must be at least 8 characters' }, { status: 400 });
    }

    const existing = await prisma.user.findUnique({ where: { email } });
    if (existing) {
      return NextResponse.json({ error: 'Email already registered' }, { status: 409 });
    }

    const passwordHash = await hashPassword(password);

    const user = await prisma.user.create({
      data: {
        email,
        name,
        passwordHash,
        status: UserStatus.PENDING,
        role: Role.USER,
      },
    });

    const token = randomToken();
    await prisma.verificationToken.create({
      data: {
        userId: user.id,
        token,
        type: 'email_verify',
        expiresAt: addHours(24),
      },
    });

    const verifyUrl = `${APP_URL}/verify?token=${token}`;
    await sendVerificationEmail(email, verifyUrl);

    return NextResponse.json({ ok: true });
  } catch (error) {
    console.error('Register error', error);
    return NextResponse.json({ error: 'Registration failed' }, { status: 500 });
  }
}
