<?php

namespace App\Http\Controllers\Api\Consultant;

use App\Http\Controllers\Controller;
use App\Models\ConsultantProfile;
use App\Models\TourRequest;
use Illuminate\Http\Request;

class ConsultantTourRequestController extends Controller
{
    public function index(Request $request)
    {
        $consultant = $this->consultant($request);

        $tourRequests = TourRequest::query()
        ->with(['listing.consultantProfile.user'])
        ->whereHas('listing.consultantProfile', fn($p0) => $p0->where('id', $consultant->id) )
        ->latest()
        ->get();

        return response()->json([
            'data' => $tourRequests
        ]);
    }

    public function update(Request $request, TourRequest $tourRequest)
    {
        $consultant = $this->consultant($request);

        // Sahiplik: tur, danışmanın kendi ilanına ait olmalı (soft-delete dahil).
        abort_unless(
            $tourRequest->listing && $tourRequest->listing->consultant_profile_id === $consultant->id,
            404
        );

        $data = $request->validate([
            'status' => ['required', 'string', 'in:confirmed,rejected,completed,cancelled'],
            'status_note' => ['nullable', 'string', 'max:200'],
        ]);

        if (! $tourRequest->canTransitionTo($data['status'])) {
            abort(422, "Bu tur '{$tourRequest->status}' durumundan '{$data['status']}' durumuna geçirilemez");
        }

        $tourRequest->update([
            'status' => $data['status'],
            // Not sadece red/iptalde anlamlı; diğer geçişlerde bayat not kalmasın.
            'status_note' => in_array($data['status'], [TourRequest::STATUS_REJECTED, TourRequest::STATUS_CANCELLED], true)
                ? ($data['status_note'] ?? null)
                : null,
        ]);

        return response()->json([
            'data' => $tourRequest->fresh()->load('listing.consultantProfile.user'),
        ]);
    }

    private function consultant(Request $request)
    {
        $consultant = $request->user()->consultantProfile;
        abort_unless($consultant && $consultant->application_status === ConsultantProfile::STATUS_APPROVED
        ,403,
        'Onaylanmış bir danışman hesabınız bulunmamaktadır');
        return $consultant; 
    }
}
