<?php

namespace App\Services\Coach;

use App\Enums\CoachDocumentType;
use App\Models\AuditLog;
use App\Models\Coach;
use App\Models\CoachDocument;
use App\Services\FileUploadService;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;

class CoachProfileService
{
    public function __construct(private readonly FileUploadService $uploader)
    {
    }

    public function updateProfile(Coach $coach, array $data): void
    {
        $old = $coach->only(['bio', 'work_history', 'experience_years', 'program_price']);

        $coach->update([
            'bio' => $data['bio'] ?? $coach->bio,
            'work_history' => $data['work_history'] ?? $coach->work_history,
            'experience_years' => $data['experience_years'] ?? $coach->experience_years,
            'program_price' => $data['program_price'] ?? $coach->program_price,
        ]);

        if (isset($data['goal_ids'])) {
            $coach->goals()->sync($data['goal_ids']);
        }

        AuditLog::record('coach.profile_updated', $coach, oldValues: $old, newValues: $coach->only(array_keys($old)));
    }

    public function updatePhoto(Coach $coach, UploadedFile $file): void
    {
        $old = $coach->photo_path;

        $result = $this->uploader->store($file, 'coach_photo', "coaches/{$coach->id}");
        $coach->update(['photo_path' => $result['path']]);

        if ($old) {
            $this->uploader->delete('public', $old);
        }

        AuditLog::record('coach.photo_updated', $coach);
    }

    public function addDocument(Coach $coach, UploadedFile $file, CoachDocumentType $type, int $uploadedByUserId): CoachDocument
    {
        return DB::transaction(function () use ($coach, $file, $type, $uploadedByUserId) {
            $result = $this->uploader->store($file, 'coach_document', "coaches/{$coach->id}/documents");

            $document = CoachDocument::create([
                'coach_id' => $coach->id,
                'type' => $type,
                'original_name' => $result['original_name'],
                'stored_path' => $result['path'],
                'mime_type' => $result['mime'],
                'size_bytes' => $result['size'],
                'uploaded_by' => $uploadedByUserId,
            ]);

            AuditLog::record('coach.document_uploaded', $document, newValues: ['type' => $type->value]);

            return $document;
        });
    }

    public function deleteDocument(CoachDocument $document): void
    {
        $this->uploader->delete('local_private', $document->stored_path);
        AuditLog::record('coach.document_deleted', $document);
        $document->delete();
    }
}
