<?php

namespace App\Services;

use App\Models\Batches;
use Carbon\Carbon;

class GenerateBatchNumberService
{
    public function generateNextBatchNo(array $data): array
    {
        $year       = Carbon::parse($data['loading_date'])->year;
        $farmId     = $data["farm_id"];
        $buildingId = $data["building_id"];

        $nextSequence = $this->getNextSequence($farmId, $buildingId, $year);

        return [
            "batch_no"       => $year . "-F" . $farmId . "-B" . $buildingId . "-" . str_pad($nextSequence, 3, "0", STR_PAD_LEFT),
            "batch_sequence" => $nextSequence,
        ];
    }

    protected function getNextSequence(int $farmId, int $buildingId, int $year): int
    {
        $activeSequences = Batches::where("farm_id", $farmId)
            ->where("building_id", $buildingId)
            ->whereYear("start_date", $year)
            ->whereNotIn("status", ["void"])
            ->orderBy("batch_sequence")
            ->pluck("batch_sequence")
            ->toArray();

        if (empty($activeSequences)) {
            return 1;
        }

        $nextSequence = 1;
        foreach ($activeSequences as $seq) {
            if ($seq > $nextSequence) {
                return $nextSequence;
            }
            $nextSequence = $seq + 1;
        }

        return $nextSequence;
    }
}
