<?php

namespace Database\Seeders;

use App\Models\Customer;
use App\Models\Membership;
use App\Models\Tier;
use Illuminate\Database\Seeder;

class MembershipSeeder extends Seeder
{
    public function run(): void
    {
        $tiers = Tier::all();

        $userIds = Customer::whereNotNull('user_id')
            ->pluck('user_id')
            ->unique()
            ->toArray();

        foreach ($userIds as $userId) {
            $totalSpending = fake()->numberBetween(0, 15000000);

            $tier = $tiers->first(function ($tier) use ($totalSpending) {
                $min = $tier->min_spending;
                $max = $tier->max_spending ?? PHP_INT_MAX;

                return $totalSpending >= $min && $totalSpending <= $max;
            });

            if (! $tier) {
                $tier = $tiers->first(); // Default to Bronze
            }

            Membership::create([
                'user_id' => $userId,
                'tier_id' => $tier->id,
                'total_spending' => $totalSpending,
            ]);
        }
    }
}
