<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\Models\RecruitmentOfferLetter;
use App\Modules\HR\Recruitment\Repositories\RecruitmentOfferLetterStatusEventRepository;

class RecruitmentOfferLetterStatusHistoryService
{
    public function __construct(
        private readonly RecruitmentOfferLetterStatusEventRepository $events,
    ) {}

    /** @param  array<string, mixed>|null  $meta */
    public function record(
        RecruitmentOfferLetter $offer,
        ?string $from,
        string $to,
        string $action,
        ?int $actorUserId,
        ?string $notes = null,
        ?array $meta = null,
    ): void {
        $this->events->create([
            'tenant_id' => (int) $offer->tenant_id,
            'offer_letter_id' => (int) $offer->id,
            'from_status' => $from,
            'to_status' => $to,
            'action' => $action,
            'notes' => $notes,
            'actor_user_id' => $actorUserId,
            'meta' => $meta,
            'created_at' => now(),
        ]);
    }

    /** @return list<array{label: string, meta: string, state: string, kind: string}> */
    public function timelineSteps(RecruitmentOfferLetter $offer): array
    {
        $rows = $this->events->listForOffer((int) $offer->tenant_id, (int) $offer->id);
        $steps = [];
        foreach ($rows as $i => $row) {
            $isLast = $i === $rows->count() - 1;
            $steps[] = [
                'label' => __('recruitment.offer_letters.actions.'.$row->action),
                'meta' => trim(
                    ($row->actor?->name ?? '—').' · '.
                    ($row->created_at?->format('Y-m-d H:i') ?? '').
                    ($row->notes ? ' — '.$row->notes : '')
                ),
                'state' => $isLast ? 'current' : 'done',
                'kind' => 'status',
            ];
        }

        return $steps;
    }
}
