<?php

namespace App\Http\Controllers;

use App\Http\Requests\SupportRequestRequest;
use App\Http\Resources\SupportRequestResource;
use App\Services\SupportRequestService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class SupportRequestController extends Controller
{
    public function __construct(
        protected SupportRequestService $service,
    ) {}

    public function index(Request $request): JsonResponse
    {
        $paginated = $this->service->paginate(
            status:  $request->input('status'),
            search:  $request->input('filter'),
            page:    $request->integer('page', 1),
            perPage: $request->integer('per_page', 10),
        );

        return $this->successResponse(payload: [
            'data'  => SupportRequestResource::collection($paginated->items()),
            'total' => $paginated->total(),
            'from'  => $paginated->firstItem() ?? 0,
            'to'    => $paginated->lastItem()  ?? 0,
        ]);
    }

    public function show(int $id): JsonResponse
    {
        $item = $this->service->findById($id);

        if (! $item) {
            return $this->errorResponse(message: __('messages.not_found'));
        }

        return $this->successResponse(payload: new SupportRequestResource($item));
    }

    public function store(SupportRequestRequest $request): JsonResponse
    {
        $user = Auth::user();

        $data = array_merge($request->validated(), [
            'user_id'   => $user?->id,
            'user_type' => $user?->type?->value,
            'name'      => $request->input('name', $user?->name),
            'email'     => $request->input('email', $user?->email),
            'phone'     => $request->input('phone', $user?->phone),
        ]);

        $item = $this->service->create($data);

        return $this->successResponse(payload: new SupportRequestResource($item), message: __('messages.created'), code: 201);
    }

    public function update(SupportRequestRequest $request, int $id): JsonResponse
    {
        $item = $this->service->updateStatus($id, $request->validated()['status'], Auth::id());

        if (! $item) {
            return $this->errorResponse(message: __('messages.not_found'));
        }

        return $this->successResponse(payload: new SupportRequestResource($item), message: __('messages.updated'));
    }
}
