<?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('id')
            ->unique()
            ->toArray();

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

            $tier = $tiers->first(function ($tier) use ($totalPoints) {
                $min = $tier->min_points;
                $max = $tier->max_points ?? PHP_INT_MAX;

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

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