<?php

namespace App\Services\Attendance;

use DateTimeImmutable;
use DateTimeZone;
use Illuminate\Support\Facades\DB;

class AttendanceAutoPublishJobService
{
    public function __construct(private AttendanceAutoPublishService $autoPublish)
    {
    }

    public function run(?DateTimeImmutable $now = null): array
    {
        $zone = $this->autoPublish->timezone();
        $now = $now ? $now->setTimezone($zone) : new DateTimeImmutable('now', $zone);
        $nowStr = $now->format('Y-m-d H:i:s');

        $cutoffDate = $this->autoPublish->secondSundayBackwardDate($now);

        $query = DB::table('attendance_day')
            ->where('status', 'submitted')
            ->where(function ($q) use ($nowStr, $cutoffDate) {
                $q->where('auto_publish_at', '<=', $nowStr)
                    ->orWhere(function ($sub) use ($cutoffDate) {
                        $sub->whereNull('auto_publish_at')
                            ->where('date', '<=', $cutoffDate);
                    });
            });

        $count = (clone $query)->count();
        if ($count > 0) {
            $query->update([
                'status' => 'published',
                'published_by' => 0,
                'published_at' => $nowStr,
                'updated_at' => $nowStr,
            ]);
        }

        return [
            'published' => $count,
            'checked_at' => $nowStr,
            'timezone' => $zone->getName(),
        ];
    }
}
