<?php

namespace App\Services\Roadmap;

use App\Models\Admin\AdminRoadmapMilestone;
use Illuminate\Database\Eloquent\Collection;

class RoadmapMilestoneService
{
    public function __construct(
        private readonly RoadmapPlanService $planService
    ) {}

    public function getMilestonesByPlan(int $planId): Collection
    {
        return AdminRoadmapMilestone::query()
            ->where('plan_id', $planId)
            ->with('assignee')
            ->orderBy('sort_order')
            ->orderBy('id')
            ->get();
    }

    public function createMilestone(array $data): AdminRoadmapMilestone
    {
        $data['created_by'] = auth()->id();

        $milestone = AdminRoadmapMilestone::create($data);
        $this->planService->recalculateProgress($milestone->plan_id);

        return $milestone;
    }

    public function updateMilestone(int $id, array $data): bool
    {
        $milestone = AdminRoadmapMilestone::findOrFail($id);
        $data['updated_by'] = auth()->id();
        $result = $milestone->update($data);

        $this->planService->recalculateProgress($milestone->plan_id);

        return $result;
    }

    public function deleteMilestone(int $id): bool
    {
        $milestone = AdminRoadmapMilestone::findOrFail($id);
        $planId = $milestone->plan_id;

        $milestone->deleted_by = auth()->id();
        $milestone->save();
        $result = $milestone->delete();

        $this->planService->recalculateProgress($planId);

        return $result;
    }

    public function toggleStatus(int $id): AdminRoadmapMilestone
    {
        $milestone = AdminRoadmapMilestone::findOrFail($id);

        if ($milestone->status === AdminRoadmapMilestone::STATUS_COMPLETED) {
            $milestone->status = AdminRoadmapMilestone::STATUS_PENDING;
            $milestone->completed_at = null;
        } else {
            $milestone->status = AdminRoadmapMilestone::STATUS_COMPLETED;
            $milestone->completed_at = now();
        }

        $milestone->updated_by = auth()->id();
        $milestone->save();

        $this->planService->recalculateProgress($milestone->plan_id);

        return $milestone;
    }
}
