<?php

namespace App\Services\Job;

use App\Models\JobModel;
use App\Services\Notification\NotificationService;
use App\Services\Support\ActivityLogger;

class JobExpiryService
{
    private JobModel $jobs;
    private NotificationService $notifications;
    private ActivityLogger $activity;

    public function __construct()
    {
        $this->jobs          = new JobModel();
        $this->notifications = new NotificationService();
        $this->activity      = new ActivityLogger();
    }

    public function runExpiryCheck(): int
    {
        $expired = $this->jobs
            ->where('status', 'published')
            ->where('expires_at <', date('Y-m-d'))
            ->findAll();

        $count = 0;
        foreach ($expired as $job) {
            $this->jobs->update($job->id, ['status' => 'expired']);

            $this->notifications->send($job->posted_by_user_id, 'job_expired', ['job_title' => $job->title]);
            $this->activity->log($job->posted_by_user_id, $job->agency_id, null, 'job_expired', ['job_id' => $job->id, 'title' => $job->title]);

            $count++;
        }

        return $count;
    }
}
