<?php

namespace App\Services\Athlete;

use App\Enums\BodyPhotoAngle;
use App\Models\AthleteAssessment;
use App\Models\AuditLog;
use App\Models\Athlete;
use App\Models\BodyMeasurement;
use App\Models\BodyPhoto;
use App\Models\LifestyleRecord;
use App\Models\MedicalRecord;
use App\Services\BmiCalculatorService;
use App\Services\FileUploadService;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;

/**
 * فرم ارزیابی (اولیه یا هر ۴ هفته — بند ۹ تا ۱۴) یک تراکنش واحد است:
 * اگر هرجایی خطا بدهد، هیچ رکورد ناقصی نباید در دیتابیس بماند.
 */
class AssessmentService
{
    public function __construct(
        private readonly BmiCalculatorService $bmiCalculator,
        private readonly FileUploadService $uploader,
    ) {
    }

    public function createAssessment(Athlete $athlete, array $data, int $createdByUserId, bool $isInitial = false): AthleteAssessment
    {
        return DB::transaction(function () use ($athlete, $data, $createdByUserId, $isInitial) {
            $bmi = $this->bmiCalculator->calculate((float) $data['weight_kg'], (int) $data['height_cm']);

            $assessment = AthleteAssessment::create([
                'athlete_id' => $athlete->id,
                'coach_id' => $data['coach_id'] ?? null,
                'assessment_date' => $data['assessment_date'] ?? now()->toDateString(),
                'weight_kg' => $data['weight_kg'],
                'height_cm' => $data['height_cm'],
                'bmi' => $bmi,
                'body_fat_percentage' => $data['body_fat_percentage'] ?? null,
                'athlete_level' => $data['athlete_level'] ?? null,
                'training_history' => $data['training_history'] ?? null,
                'goal_id' => $data['goal_id'] ?? null,
                'coach_notes' => $data['coach_notes'] ?? null,
                'is_initial' => $isInitial,
                'created_by' => $createdByUserId,
            ]);

            BodyMeasurement::create([
                'assessment_id' => $assessment->id,
                'waist_cm' => $data['waist_cm'] ?? null,
                'arm_cm' => $data['arm_cm'] ?? null,
                'thigh_cm' => $data['thigh_cm'] ?? null,
                'chest_cm' => $data['chest_cm'] ?? null,
            ]);

            LifestyleRecord::create([
                'assessment_id' => $assessment->id,
                'occupation' => $data['occupation'] ?? null,
                'job_type' => $data['job_type'] ?? null,
                'avg_sleep_hours' => $data['avg_sleep_hours'] ?? null,
                'stress_level' => $data['stress_level'] ?? null,
                'smokes' => $data['smokes'] ?? false,
                'drinks_alcohol' => $data['drinks_alcohol'] ?? false,
                'can_eat_regularly' => $data['can_eat_regularly'] ?? null,
                'can_eat_healthy' => $data['can_eat_healthy'] ?? null,
                'additional_notes' => $data['lifestyle_notes'] ?? null,
            ]);

            MedicalRecord::create([
                'assessment_id' => $assessment->id,
                'physical_problems' => $data['physical_problems'] ?? null,
                'movement_disorders' => $data['movement_disorders'] ?? null,
                'skeletal_problems' => $data['skeletal_problems'] ?? null,
                'current_medications' => $data['current_medications'] ?? null,
                'lab_tests' => $data['lab_tests'] ?? null,
                'other_notes' => $data['medical_notes'] ?? null,
            ]);

            // اطلاعات پایه‌ی athletes هم به‌روزرسانی می‌شود تا «آخرین قد/وزن» برای نمایش سریع در دسترس باشد
            // (تاریخچه‌ی واقعی همیشه در athlete_assessments حفظ می‌شود — بند ۴۴)
            $athlete->update([
                'height_cm' => $data['height_cm'],
                'weight_kg' => $data['weight_kg'],
            ]);

            AuditLog::record('assessment.created', $assessment, newValues: ['is_initial' => $isInitial]);

            return $assessment;
        });
    }

    public function addPhoto(AthleteAssessment $assessment, UploadedFile $file, BodyPhotoAngle $angle, int $uploadedByUserId): BodyPhoto
    {
        $result = $this->uploader->store($file, 'body_photo', "athletes/{$assessment->athlete_id}/assessments/{$assessment->id}");

        $photo = BodyPhoto::create([
            'assessment_id' => $assessment->id,
            'angle' => $angle,
            'original_name' => $result['original_name'],
            'stored_path' => $result['path'],
            'mime_type' => $result['mime'],
            'size_bytes' => $result['size'],
            'uploaded_by' => $uploadedByUserId,
        ]);

        AuditLog::record('assessment.photo_uploaded', $photo, newValues: ['angle' => $angle->value]);

        return $photo;
    }
}
