<?php

namespace App\Services\Coach;

use App\Enums\CoachRequestStatus;
use App\Models\AuditLog;
use App\Models\Athlete;
use App\Models\Coach;
use App\Models\CoachRequest;
use App\Services\NotificationService;
use RuntimeException;

/**
 * نسخه به‌روزشده Phase 12 — نسخه Phase 5 را جایگزین کنید.
 * تغییر: TODOهای Notification با فراخوانی واقعی NotificationService جایگزین شدند.
 */
class CoachRequestService
{
    public function __construct(private readonly NotificationService $notifier)
    {
    }

    public function sendRequest(Athlete $athlete, Coach $coach, ?string $message = null): CoachRequest
    {
        if (! $coach->isApproved()) {
            throw new RuntimeException('این مربی در حال حاضر تأیید نشده است.');
        }

        $existingActive = $athlete->coachRequests()
            ->where('coach_id', $coach->id)
            ->whereIn('status', [CoachRequestStatus::Pending, CoachRequestStatus::Accepted])
            ->exists();

        if ($existingActive) {
            throw new RuntimeException('شما قبلاً برای این مربی درخواست فعال دارید.');
        }

        $request = CoachRequest::create([
            'athlete_id' => $athlete->id,
            'coach_id' => $coach->id,
            'status' => CoachRequestStatus::Pending,
            'athlete_message' => $message,
        ]);

        AuditLog::record('coach_request.created', $request);

        $this->notifier->send(
            $coach->user,
            'coach_request.created',
            'درخواست همکاری جدید',
            $athlete->user->fullName().' درخواست همکاری ارسال کرد.',
            route('coach.requests.index'),
        );

        return $request;
    }

    public function accept(CoachRequest $request): void
    {
        $request->update([
            'status' => CoachRequestStatus::Accepted,
            'responded_at' => now(),
        ]);

        AuditLog::record('coach_request.accepted', $request);

        $this->notifier->send(
            $request->athlete->user,
            'coach_request.accepted',
            'درخواست شما پذیرفته شد',
            $request->coach->user->fullName().' درخواست همکاری شما را پذیرفت.',
            route('athlete.requests.index'),
        );
    }

    public function reject(CoachRequest $request, ?string $note = null): void
    {
        $request->update([
            'status' => CoachRequestStatus::Rejected,
            'coach_response_note' => $note,
            'responded_at' => now(),
        ]);

        AuditLog::record('coach_request.rejected', $request);

        $this->notifier->send(
            $request->athlete->user,
            'coach_request.rejected',
            'درخواست شما رد شد',
            $note,
            route('athlete.requests.index'),
        );
    }

    public function setPrice(CoachRequest $request, float $price): void
    {
        $old = $request->price;

        $request->update(['price' => $price]);

        AuditLog::record('coach_request.price_set', $request, oldValues: ['price' => $old], newValues: ['price' => $price]);

        $this->notifier->send(
            $request->athlete->user,
            'coach_request.price_set',
            'قیمت برنامه تعیین شد',
            number_format($price).' تومان — می‌توانید رسید پرداخت را ارسال کنید.',
            route('athlete.requests.index'),
        );
    }
}
