package models

import (
	"errors"
	"net/http"
)

type AppError struct {
	Status  int    `json:"-"`
	Code    string `json:"code"`
	Message string `json:"error"`
	Details string `json:"details,omitempty"`
}

func (e *AppError) Error() string {
	return e.Message
}

var (
	ErrAuthRequired    = &AppError{Status: http.StatusUnauthorized, Code: "AUTH_REQUIRED", Message: "Authentication required"}
	ErrAuthInvalid     = &AppError{Status: http.StatusUnauthorized, Code: "AUTH_INVALID", Message: "Invalid credentials"}
	ErrForbidden       = &AppError{Status: http.StatusForbidden, Code: "FORBIDDEN", Message: "Permission denied"}
	ErrNotFound        = &AppError{Status: http.StatusNotFound, Code: "NOT_FOUND", Message: "Resource not found"}
	ErrValidation      = &AppError{Status: http.StatusBadRequest, Code: "VALIDATION_ERROR", Message: "Validation failed"}
	ErrConflict        = &AppError{Status: http.StatusConflict, Code: "CONFLICT", Message: "Resource conflict"}
	ErrRateLimited     = &AppError{Status: http.StatusTooManyRequests, Code: "RATE_LIMITED", Message: "Too many requests"}
	ErrInternal        = &AppError{Status: http.StatusInternalServerError, Code: "INTERNAL", Message: "Internal server error"}
)

func NewValidationError(detail string) *AppError {
	return &AppError{Status: http.StatusBadRequest, Code: "VALIDATION_ERROR", Message: detail}
}

func NewConflictError(detail string) *AppError {
	return &AppError{Status: http.StatusConflict, Code: "CONFLICT", Message: detail}
}

func NewNotFoundError(detail string) *AppError {
	return &AppError{Status: http.StatusNotFound, Code: "NOT_FOUND", Message: detail}
}

func NewForbiddenError(detail string) *AppError {
	return &AppError{Status: http.StatusForbidden, Code: "FORBIDDEN", Message: detail}
}

func IsAppError(err error) (*AppError, bool) {
	var appErr *AppError
	if errors.As(err, &appErr) {
		return appErr, true
	}
	return nil, false
}
