<?php

namespace App\Traits;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;

trait RespondsWithHttp
{
    /**
     * Check if the request expects a JSON response.
     */
    protected function expectsJson(Request $request): bool
    {
        return $request->expectsJson() || $request->query('api') === 'true';
    }

    /**
     * Return a response based on request type.
     *
     * @param Request $request
     * @param mixed $data Data for successful response
     * @param string|null $successMessage
     * @param string|null $redirectRoute Route name for web redirect
     * @param int $status HTTP status code
     * @return JsonResponse|RedirectResponse
     */
    protected function respond(Request $request, $data = [], ?string $successMessage = null, ?string $redirectRoute = null, int $status = 200)
    {
        if ($this->expectsJson($request)) {
            return response()->json([
                'success' => true,
                'message' => $successMessage,
                'data' => $data,
            ], $status);
        }

        if ($redirectRoute) {
            return Redirect::route($redirectRoute)->with('success', $successMessage);
        }

        return Redirect::back()->with('success', $successMessage);
    }

    /**
     * Return an error response based on request type.
     *
     * @param Request $request
     * @param string $errorMessage
     * @param int $status HTTP status code
     * @param array $errors Additional error details
     * @return JsonResponse|RedirectResponse
     */
    protected function respondWithError(Request $request, string $errorMessage, int $status = 400, array $errors = [])
    {
        if ($this->expectsJson($request)) {
            return response()->json([
                'success' => false,
                'message' => $errorMessage,
                'errors' => $errors,
            ], $status);
        }

        return Redirect::back()->with('error', $errorMessage)->withErrors($errors);
    }
}