<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\HourRegistration\Services;

use Illuminate\Support\Facades\DB;
use Maestro\Core\Modules\HourRegistration\Enums\HourLineApprovalStatus;
use Maestro\Core\Modules\HourRegistration\Enums\HourRegistrationType;
use Maestro\Core\Modules\HourRegistration\Enums\HourWorkflowStatus;
use Maestro\Core\Modules\HourRegistration\Models\HourTimesheetWeek;

final class HourTimesheetUnlockService
{
    /** Admin-only: clears approval lock so the employee may edit again. */
    public function unlock(HourTimesheetWeek $week): HourTimesheetWeek
    {
        return DB::transaction(function () use ($week) {
            $week->load('lines');

            foreach ($week->lines as $line) {
                if ($line->registration_type === HourRegistrationType::Internal) {
                    $line->line_approval_status = HourLineApprovalStatus::Approved;

                    $line->approved_by_id = null;

                    $line->approved_at = null;

                    $line->reject_reason = null;
                } else {
                    $line->line_approval_status = HourLineApprovalStatus::Pending;

                    $line->approved_by_id = null;

                    $line->approved_at = null;

                    $line->reject_reason = null;
                }

                $line->save();
            }

            $week->workflow_status = HourWorkflowStatus::Draft;

            $week->submitted_at = null;

            $week->save();

            return $week->fresh(['lines']);
        });
    }
}
