<?php

namespace App\Http\Controllers\Api\Support;

use App\Http\Controllers\Api\Core\BaseApiController;
use App\Http\Requests\Support\SupportRequestIndexRequest;
use App\Http\Requests\Support\SupportRequestStoreRequest;
use App\Http\Resources\Support\SupportRequestCollection;
use App\Http\Resources\Support\SupportRequestResource;
use App\Models\SupportRequest;
use App\Services\Support\SupportRequestService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;

class SupportController extends BaseApiController
{
    public function __construct(private SupportRequestService $supportService)
    {
        parent::__construct();
    }

    public function index(SupportRequestIndexRequest $request): JsonResponse
    {
        $guard = $this->authenticatedUserIdOrUnauthorized();
        if ($guard instanceof JsonResponse) {
            return $guard;
        }

        $this->authorize('viewAny', SupportRequest::class);

        $filters = $request->validated();
        $page = (int) ($filters['page'] ?? 1);
        $perPage = (int) ($filters['per_page'] ?? 20);

        $isAdmin = auth()->user()?->roles()
            ->pluck('roles.name')
            ->map(fn ($name) => strtolower((string) $name))
            ->intersect(['administrator', 'admin', 'principal', 'vice_principal', 'vice-principal'])
            ->isNotEmpty();

        $paginator = $this->supportService->list($guard, $filters, $page, $perPage, $isAdmin);
        $collection = new SupportRequestCollection($paginator);

        return $this->success([
            'requests' => $collection->toArray($request),
            'meta' => $collection->with($request)['meta'] ?? null,
        ]);
    }

    public function store(SupportRequestStoreRequest $request): JsonResponse
    {
        $guard = $this->authenticatedUserIdOrUnauthorized();
        if ($guard instanceof JsonResponse) {
            return $guard;
        }

        $user = auth()->user();
        if (! $user) {
            return $this->error('Unauthorized.', Response::HTTP_UNAUTHORIZED);
        }

        $this->authorize('create', SupportRequest::class);

        $payload = $request->validated();
        $payload['user_email'] = $user->email ?? null;
        $payload['user_name'] = trim(($user->firstname ?? '') . ' ' . ($user->lastname ?? ''));

        try {
            $result = $this->supportService->create((int) $user->id, $payload);
        } catch (\Throwable $e) {
            Log::error('Support request failed: ' . $e->getMessage());
            return $this->error('Unable to submit support request.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return $this->success([
            'request' => new SupportRequestResource($result['record']),
            'email_sent' => $result['email_sent'],
        ], 'Support request submitted.', Response::HTTP_CREATED);
    }

    public function teacher(): JsonResponse
    {
        return $this->success([
            'page' => 'teacher_support',
        ]);
    }

    /**
     * @return int|JsonResponse
     */
    private function authenticatedUserIdOrUnauthorized(): int|JsonResponse
    {
        $userId = (int) (auth()->id() ?? 0);
        if ($userId <= 0) {
            return $this->error('Unauthorized.', Response::HTTP_UNAUTHORIZED);
        }

        return $userId;
    }
}
