<?php

namespace App\Support;

use App\Models\AttendanceLeaveApplication;
use App\Models\AttendancePunch;
use App\Models\PermanentEmployeeSalaryPayment;
use Illuminate\Support\Facades\DB;

class ClearAttendanceRecords
{
    /**
     * Remove all punch and leave rows shown in attendance records (devices/enrollments unchanged).
     *
     * @return array{punches: int, leaves: int, salary_drafts_refreshed: int}
     */
    public static function run(): array
    {
        return DB::transaction(function (): array {
            $punchCount = AttendancePunch::query()->count();
            $leaveCount = AttendanceLeaveApplication::query()->count();

            AttendancePunch::query()->delete();
            AttendanceLeaveApplication::query()->delete();

            $refreshed = 0;

            PermanentEmployeeSalaryPayment::query()
                ->where('status', SalaryPaymentStatus::DRAFT)
                ->with('permanentEmployee')
                ->get()
                ->each(function (PermanentEmployeeSalaryPayment $payment) use (&$refreshed): void {
                    if ($payment->refreshDraftFromContract()) {
                        $refreshed++;
                    }
                });

            return [
                'punches' => $punchCount,
                'leaves' => $leaveCount,
                'salary_drafts_refreshed' => $refreshed,
            ];
        });
    }
}
