<?php

namespace App\Services;

use App\Models\AuditLog;
use App\Models\CoachRequest;
use App\Models\Review;
use App\Models\User;

/**
 * نسخه به‌روزشده — نسخه Phase 13 را جایگزین کنید (اصلاح Workflow دو‌مرحله‌ای، بند ۳۴).
 */
class ReviewService
{
    public function submit(CoachRequest $request, int $rating, ?string $comment): Review
    {
        $review = Review::create([
            'coach_request_id' => $request->id,
            'rating' => $rating,
            'comment' => $comment,
            'status' => 'pending_coach', // مرحله ۱
        ]);

        AuditLog::record('review.submitted', $review, newValues: ['rating' => $rating]);

        return $review;
    }

    /**
     * مرحله ۱: مربی تأیید می‌کند → می‌رود به pending_admin (نه مستقیم approved).
     */
    public function coachApprove(Review $review): void
    {
        $review->update([
            'status' => 'pending_admin',
            'coach_moderated_at' => now(),
        ]);

        AuditLog::record('review.coach_approved', $review);
    }

    public function coachReject(Review $review, string $reason): void
    {
        $review->update([
            'status' => 'rejected_by_coach',
            'rejection_reason' => $reason,
            'coach_moderated_at' => now(),
        ]);

        AuditLog::record('review.coach_rejected', $review, newValues: ['reason' => $reason]);
    }

    /**
     * مرحله ۲: Admin تأیید می‌کند → عمومی می‌شود.
     */
    public function adminApprove(Review $review, User $admin): void
    {
        $review->update([
            'status' => 'approved',
            'rejection_reason' => null,
            'admin_moderated_by' => $admin->id,
            'admin_moderated_at' => now(),
        ]);

        AuditLog::record('review.admin_approved', $review);
    }

    public function adminReject(Review $review, User $admin, string $reason): void
    {
        $review->update([
            'status' => 'rejected_by_admin',
            'rejection_reason' => $reason,
            'admin_moderated_by' => $admin->id,
            'admin_moderated_at' => now(),
        ]);

        AuditLog::record('review.admin_rejected', $review, newValues: ['reason' => $reason]);
    }
}
