import express from 'express';
import {PrismaClient} from '../../generated/prisma';
import Authenticator from '../auth/Authenticator';

const router = express.Router();
const prisma = new PrismaClient();

router.post('/', async (req, res) => {
  const {username, email, password} = req.body;

  console.log(req.body);

  // Check secret header
  const secret = req.get('x-secret') || req.headers['x-secret'];
  if (secret !== 'al3110e') {
    return res.status(403).json({status: 'error', message: 'Forbidden'});
  }

  // Validate required fields
  if (!username || !email || !password) {
    return res.status(400).json({
      status: 'error',
      message: 'Username, email, and password are required'
    });
  }

  // Basic email validation
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    return res.status(400).json({status: 'error', message: 'Invalid email format'});
  }

  // Password strength validation
  if (password.length < 6) {
    return res.status(400).json({
      status: 'error',
      message: 'Password must be at least 8 characters long'
    });
  }

  try {
    const hashedPassword = await Authenticator.hashPassword(password);
    const user = await prisma.users.create({
      data: {
        username,
        email,
        hashed_password: hashedPassword
      }
    });

    // Return user without sensitive data
    return res.status(201).json({
      id: user.id,
      username: user.username,
      email: user.email,
      created_at: user.created_at
    });
  } catch (error: any) {
    console.error(error.message);

    // Handle duplicate username or email
    if (error.code === 'P2002') {
      const field = error.meta?.target?.[0] || 'username or email';
      return res.status(409).json({
        status: 'error',
        message: `A user with this ${field} already exists`
      });
    }

    return res.status(500).json({status: 'error', message: 'Internal server error'});
  }
});

router.post('/login', async (req, res) => {
  const {username, password} = req.body;

  if (!username || !password) {
    return res.status(400).json({status: 'error', message: 'Username and password are required'});
  }

  try {
    const user = await prisma.users.findUnique({where: {username}});

    if (!user) {
      return res.status(401).json({status: 'error', message: 'Invalid credentials'});
    }

    const isPasswordValid = await Authenticator.verifyPassword(password, user.hashed_password);

    if (!isPasswordValid) {
      return res.status(401).json({status: 'error', message: 'Invalid credentials'});
    }

    // TODO: Generate a JWT token and set it as a cookie
    return res.status(200).json({
      status: 'ok',
      user: {
        id: user.id,
        username: user.username,
        email: user.email
      }
    });
  } catch (error: any) {
    console.error(error.message);
    return res.status(500).json({status: 'error', message: 'Internal server error'});
  }
});

router.post('/logout', async (req, res) => {
  res.clearCookie('token');
  res.status(200).json({status: 'ok', message: 'Logged out successfully'});
});

export default router;
