<?php

namespace Database\Seeders;

use App\Models\User;
use Coderstm\Models\Plan;
use Coderstm\Enum\AppStatus;
use Coderstm\Models\Address;
use Illuminate\Database\Seeder;
use Coderstm\Models\Cashier\Subscription;
use Illuminate\Console\View\Components\TwoColumnDetail;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;

class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $startTime = microtime(true);
        try {
            User::factory()->count(10)
                ->create()
                ->each(function ($user) {
                    $user->updateOrCreateAddress(Address::factory()->make()->toArray());
                    if ($user->status == AppStatus::ACTIVE) {
                        try {
                            Subscription::withoutEvents(function () use ($user) {
                                if ($plan = Plan::inRandomOrder()->first()) {
                                    if ($plan->is_custom) {
                                        $price = $plan->prices[0];
                                    } else {
                                        $price = $plan->prices[rand(0, 1)]; // 0 => month and 1 => year
                                    }
                                }

                                // Generate a fake subscription
                                $subscription = Subscription::create([
                                    'user_id' => $user->id,
                                    'type' => 'default',
                                    'stripe_id' => fake()->unique()->lexify('sub_????????????????'),
                                    'stripe_status' => 'active',
                                    'stripe_price' => $price->stripe_id,
                                    'quantity' => 1,
                                    'trial_ends_at' => now()->addDays(14),
                                    'created_at' => $user->created_at,
                                    'ends_at' => rand(0, 1) ? $user->created_at->addMonths(rand(5, 8)) : null,
                                ]);

                                // Associate the subscription with the user
                                $user->subscriptions()->save($subscription);
                            });
                        } catch (\Exception $e) {
                            throw $e;
                        }
                    }
                });
        } catch (\Exception $e) {
            $runTime = number_format((microtime(true) - $startTime) * 1000);
            with(new TwoColumnDetail($this->command->getOutput()))->render(
                $e->getMessage(),
                "<fg=gray>$runTime ms</> <fg=red;options=bold>ERROR</>"
            );

            $this->command->getOutput()->writeln('');
        }
    }
}
