<?php

namespace App\Services\Coach;

use App\Models\AuditLog;
use App\Models\Athlete;
use App\Models\Coach;
use App\Models\NutritionPlan;

class NutritionPlanService
{
    public function create(Athlete $athlete, Coach $coach, array $data): NutritionPlan
    {
        $plan = NutritionPlan::create([
            'athlete_id' => $athlete->id,
            'coach_id' => $coach->id,
            'name' => $data['name'],
            'description' => $data['description'] ?? null,
            'status' => 'draft',
        ]);

        AuditLog::record('nutrition_plan.created', $plan, newValues: ['name' => $plan->name]);

        return $plan;
    }

    public function update(NutritionPlan $plan, array $data): void
    {
        $old = $plan->only(['name', 'status']);

        $plan->update([
            'name' => $data['name'],
            'description' => $data['description'] ?? null,
            'status' => $data['status'] ?? $plan->status->value,
        ]);

        AuditLog::record('nutrition_plan.updated', $plan, oldValues: $old, newValues: $plan->only(array_keys($old)));
    }

    public function archive(NutritionPlan $plan): void
    {
        $plan->update(['status' => 'archived']);
        AuditLog::record('nutrition_plan.archived', $plan);
    }
}
