<?php

namespace App\Console\Commands;

use App\Models\FeedDelivery;
use App\Models\FeedSchedule;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ProcessFeedSchedule extends Command
{
    protected $signature = 'feed:schedule-process {time?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Process any pending feed schedules for a specific time and adjust stock accordingly';

    public function handle(): int
    {
        $time = $this->argument('time') ?? now()->format('H:i');

        $schedules = FeedSchedule::with('feeds.unit')->whereTime('scheduled_at', $time)->get();

        if ($schedules->isEmpty()) {
            $this->info("No schedules found for time: {$time}");

            return 0;
        }

        foreach ($schedules as $schedule) {
            foreach ($schedule->feeds as $feed) {
                if ($feed->stock < $feed->pivot->quantity) {
                    $this->error("Stock pakan '{$feed->name}' tidak cukup untuk jadwal '{$schedule->scheduled_at->format('H:i')}'. Dibutuhkan: {$feed->pivot->quantity}, Tersedia: {$feed->stock}");

                    return 1;
                }
            }

            try {
                DB::transaction(function () use ($schedule) {
                    foreach ($schedule->feeds as $feed) {
                        FeedDelivery::create([
                            'feed_id' => $feed->id,
                            'quantity' => $feed->pivot->quantity,
                            'delivered_at' => now(),
                        ]);
                    }
                });
            } catch (\Exception $e) {
                $this->error('Gagal memproses jadwal pakan: '.$e->getMessage());

                return 1;
            }
        }

        $this->info('Processed '.$schedules->count()." feed schedules for time: {$time}");

        return 0;
    }
}
