<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Participant\Models\Participant;
use App\Domain\Shared\Models\ServiceRequest;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ServiceRequestController extends Controller
{
    public function create(Request $request): JsonResponse
    {
        $request->validate([
            'participant_uuid' => 'required|string',
            'type' => 'required|in:freeze,unfreeze,transfer,cancellation,other',
            'reason' => 'required|string|max:1000',
            'metadata' => 'nullable|array',
        ]);

        $user = $request->user();
        $participant = $this->findAuthorized($request->participant_uuid, $user);

        $existingPending = ServiceRequest::where('participant_id', $participant->id)
            ->where('type', $request->type)
            ->where('status', 'pending')
            ->first();

        if ($existingPending) {
            return response()->json([
                'error' => 'duplicate_request',
                'message' => 'يوجد طلب مماثل قيد المراجعة بالفعل',
                'data' => [
                    'uuid' => $existingPending->uuid,
                    'created_at' => $existingPending->created_at?->toIso8601String(),
                ],
            ], 422);
        }

        $serviceRequest = ServiceRequest::create([
            'academy_id' => $participant->academy_id,
            'user_id' => $user->id,
            'participant_id' => $participant->id,
            'type' => $request->type,
            'status' => 'pending',
            'reason' => $request->reason,
            'metadata' => $request->metadata ?? [],
        ]);

        return response()->json([
            'success' => true,
            'message' => 'تم إرسال الطلب بنجاح وسيتم مراجعته',
            'data' => [
                'uuid' => $serviceRequest->uuid,
                'type' => $serviceRequest->type,
                'status' => $serviceRequest->status,
            ],
        ]);
    }

    public function index(Request $request): JsonResponse
    {
        $user = $request->user();
        $participantUuid = $request->query('participant_uuid');

        $query = ServiceRequest::where('user_id', $user->id)
            ->with('participant:id,uuid,person_id')
            ->orderByDesc('created_at');

        if ($participantUuid) {
            $participant = Participant::where('uuid', $participantUuid)->first();
            if ($participant) {
                $query->where('participant_id', $participant->id);
            }
        }

        $requests = $query->paginate(15);

        return response()->json([
            'data' => $requests->map(fn ($r) => [
                'uuid' => $r->uuid,
                'type' => $r->type,
                'type_label' => $this->typeLabel($r->type),
                'status' => $r->status,
                'status_label' => $this->statusLabel($r->status),
                'reason' => $r->reason,
                'admin_notes' => $r->admin_notes,
                'participant_uuid' => $r->participant?->uuid,
                'created_at' => $r->created_at?->toIso8601String(),
                'handled_at' => $r->handled_at?->toIso8601String(),
            ]),
            'meta' => [
                'current_page' => $requests->currentPage(),
                'last_page' => $requests->lastPage(),
                'per_page' => $requests->perPage(),
                'total' => $requests->total(),
            ],
        ]);
    }

    public function cancel(string $uuid, Request $request): JsonResponse
    {
        $user = $request->user();

        $serviceRequest = ServiceRequest::where('uuid', $uuid)
            ->where('user_id', $user->id)
            ->where('status', 'pending')
            ->firstOrFail();

        $serviceRequest->update(['status' => 'cancelled']);

        return response()->json([
            'success' => true,
            'message' => 'تم إلغاء الطلب',
        ]);
    }

    private function typeLabel(string $type): string
    {
        return match ($type) {
            'freeze' => 'طلب تجميد',
            'unfreeze' => 'طلب إلغاء تجميد',
            'transfer' => 'طلب نقل',
            'cancellation' => 'طلب إلغاء اشتراك',
            'other' => 'طلب آخر',
            default => $type,
        };
    }

    private function statusLabel(string $status): string
    {
        return match ($status) {
            'pending' => 'قيد المراجعة',
            'approved' => 'تمت الموافقة',
            'rejected' => 'مرفوض',
            'cancelled' => 'ملغي',
            default => $status,
        };
    }

    private function findAuthorized(string $uuid, $user): Participant
    {
        $participant = Participant::where('uuid', $uuid)->firstOrFail();
        $personId = $user->person_id;

        if (!$personId) {
            abort(403, 'غير مصرح لك بالوصول لهذا المشترك');
        }

        if ($participant->person_id === $personId) {
            return $participant;
        }

        $guardian = \App\Domain\Identity\Models\Guardian::where('person_id', $personId)->first();
        if ($guardian && $guardian->participants()->where('participants.id', $participant->id)->exists()) {
            return $participant;
        }

        abort(403, 'غير مصرح لك بالوصول لهذا المشترك');
    }
}
