local ReplicatedStorage = game:GetService("ReplicatedStorage")

local GameConfig = require(ReplicatedStorage.Shared.GameConfig)
local LootTables = require(ReplicatedStorage.Shared.LootTables)
local Economy = require(ReplicatedStorage.Shared.Economy)
local WeightedRandom = require(ReplicatedStorage.Shared.WeightedRandom)

local ConveyorService = {}
ConveyorService.__index = ConveyorService

local function getEligibleEggTypes(conveyorLevel)
	local entries = {}
	for eggType, def in pairs(LootTables.EggTypes) do
		if conveyorLevel >= def.minConveyorLevel then
			table.insert(entries, { id = eggType, weight = 100 - (def.minConveyorLevel * 8) })
		end
	end
	return entries
end

function ConveyorService:RefreshOffers(state, nowUnix)
	local rng = Random.new(nowUnix + state.conveyorLevel)
	local pool = getEligibleEggTypes(state.conveyorLevel)
	local offers = {}
	for _ = 1, GameConfig.Conveyor.OfferCount do
		local eggType = WeightedRandom.PickId(rng, pool)
		local eggDef = LootTables.EggTypes[eggType]
		table.insert(offers, { eggType = eggType, price = eggDef.price })
	end
	state.conveyorOffers = offers
	state.lastOfferRefreshAt = nowUnix
end

function ConveyorService:ShouldRefresh(state, nowUnix)
	return (nowUnix - state.lastOfferRefreshAt) >= GameConfig.Conveyor.RefreshSeconds
end

function ConveyorService:TryUpgrade(state)
	if state.conveyorLevel >= GameConfig.Conveyor.MaxLevel then
		return false, "ConveyorMaxLevel"
	end
	local cost = Economy.GetConveyorUpgradeCost(state.conveyorLevel)
	if state.coins < cost then
		return false, "NotEnoughCoins"
	end

	state.coins -= cost
	state.conveyorLevel += 1
	return true, nil
end

function ConveyorService:FindOffer(state, eggType)
	for _, offer in ipairs(state.conveyorOffers) do
		if offer.eggType == eggType then
			return offer
		end
	end
	return nil
end

return ConveyorService
