import { Router, Request, Response } from 'express';
import { AuditAction } from '@prisma/client';
import { prisma } from '../../lib/prisma';
import { authenticate } from '../../middleware/auth';
import { validate } from '../../middleware/validate';
import { loginSchema, refreshSchema, logoutSchema, verifyPasswordSchema } from './auth.schemas';
import * as authService from './auth.service';
const router = Router();

router.post('/login', validate(loginSchema), async (req: Request, res: Response) => {
  const { email, password } = req.body;
  const result = await authService.login(email, password);

  // Audit log the login
  await prisma.auditLog.create({
    data: {
      userId: result.user.id,
      action: AuditAction.USER_LOGIN,
      details: { email: result.user.email },
      ipAddress: req.ip,
    },
  });

  res.json(result);
});

router.post('/refresh', validate(refreshSchema), async (req: Request, res: Response) => {
  const { refreshToken } = req.body;
  const result = await authService.refresh(refreshToken);
  res.json(result);
});

router.post('/logout', validate(logoutSchema), async (req: Request, res: Response) => {
  const { refreshToken } = req.body;
  await authService.logout(refreshToken);
  res.json({ message: 'Logged out' });
});

router.post(
  '/verify-password',
  authenticate,
  validate(verifyPasswordSchema),
  async (req: Request, res: Response) => {
    const { password } = req.body;
    const valid = await authService.verifyPassword(req.user!.id, password);
    if (!valid) {
      res.status(401).json({ error: { message: 'Invalid password', code: 'INVALID_PASSWORD' } });
      return;
    }
    res.json({ verified: true });
  }
);

router.get('/me', authenticate, async (req: Request, res: Response) => {
  const user = await authService.getMe(req.user!.id);
  res.json({ user });
});

export default router;
