<?php

namespace Database\Seeders\Tenant;

use App\Facades\Settings;
use App\ScheduledTasks\StockSyncSchedule;
use Illuminate\Database\Seeder;
use Mtc\MercuryDataModels\ScheduledTask;

class StockSyncSystemTaskSeeder extends Seeder
{
    /**
     * Create (or refresh) the read-only system task that surfaces the DMS stock sync in
     * the scheduled-tasks admin. Its timetable mirrors the current stock-sync-frequency
     * setting so behaviour is unchanged; the task is managed_by = system, so the admin can
     * view it but not edit, delete or run it manually.
     *
     * @return void
     */
    public function run(): void
    {
        // Match the existing system stock-sync task by its action, not its name, so a
        // rename updates the existing row rather than leaving an orphan behind. The name is
        // generic ("Stock sync") because the underlying job syncs every enabled DMS provider,
        // not only AutoTrader.
        $task = ScheduledTask::query()
            ->where('managed_by', ScheduledTask::MANAGED_BY_SYSTEM)
            ->whereHas('actions', fn ($query) => $query->where('action_type', 'stock-sync'))
            ->first()
            ?? new ScheduledTask(['managed_by' => ScheduledTask::MANAGED_BY_SYSTEM]);

        $task->fill([
            'name' => 'Stock sync',
            'enabled' => true,
            'overlap_policy' => ScheduledTask::OVERLAP_SKIP,
            'trigger_type' => ScheduledTask::TRIGGER_SCHEDULE,
            'schedule_rules' => StockSyncSchedule::rulesForFrequency(Settings::get('stock-sync-frequency')),
        ]);
        $task->save();

        $task->actions()->updateOrCreate(
            ['order' => 1],
            ['action_type' => 'stock-sync', 'config' => [], 'run_when' => 'on_success']
        );
    }
}
