import { Request, Response, NextFunction } from 'express';
import { Prisma } from '@prisma/client';

export class AppError extends Error {
  constructor(
    public statusCode: number,
    public message: string,
    public isOperational = true
  ) {
    super(message);
    Object.setPrototypeOf(this, AppError.prototype);
  }
}

export const errorHandler = (
  err: Error | AppError,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  console.error('Error:', err);

  // Handle Prisma errors
  if (err instanceof Prisma.PrismaClientKnownRequestError) {
    if (err.code === 'P2002') {
      return res.status(409).json({
        success: false,
        message: 'سجل مكرر - Duplicate record',
        error: 'DUPLICATE_RECORD',
      });
    }
    if (err.code === 'P2025') {
      return res.status(404).json({
        success: false,
        message: 'السجل غير موجود - Record not found',
        error: 'RECORD_NOT_FOUND',
      });
    }
  }

  // Handle validation errors
  if (err instanceof Prisma.PrismaClientValidationError) {
    const detail = process.env.NODE_ENV !== 'production' ? err.message : undefined;
    return res.status(400).json({
      success: false,
      message: 'بيانات غير صالحة - Invalid data',
      error: 'VALIDATION_ERROR',
      ...(detail && { detail }),
    });
  }

  // Handle custom app errors
  if (err instanceof AppError) {
    return res.status(err.statusCode).json({
      success: false,
      message: err.message,
      error: err.message,
    });
  }

  // Default error
  res.status(500).json({
    success: false,
    message: 'خطأ في الخادم - Internal server error',
    error: process.env.NODE_ENV === 'development' ? err.message : 'INTERNAL_ERROR',
  });
};

