<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\Purchase;
use App\Models\PurchaseItem;
use App\Models\User;
use App\Models\Wine;


class PurchaseSeeder extends Seeder
{
    use WithoutModelEvents;

    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Get customer user (or any user)
        $customer = User::where('role', 'customer')->first() ?? User::first();

        if (! $customer) {
            if ($this->command) {
                $this->command->warn('No users found. Skipping PurchaseSeeder.');
            }
            return;
        }

        $wines = Wine::where('status', 'ready')->get();

        if ($wines->isEmpty()) {
            if ($this->command) {
                $this->command->warn('No wines available. Skipping PurchaseSeeder.');
            }
            return;
        }

        $winesByName = $wines->keyBy('wine_name');

        $orders = [
            // Recent orders (within last 30 days)
            [
                'note' => "Name: John Doe\nPhone: +43 123 456 789\nStreet: 123 Wine Street\nCity: Vienna\nPostal Code: 1010\nCountry: Austria",
                'status' => 'shipped',
                'purchased_at' => now()->subDays(6),
                'items' => [
                    ['wine' => $wines->random(), 'quantity' => 2],
                    ['wine' => $wines->random(), 'quantity' => 1],
                ],
            ],
            [
                'note' => "Name: John Doe\nPhone: +43 123 456 789\nStreet: 456 Grape Avenue\nCity: Salzburg\nPostal Code: 5020\nCountry: Austria",
                'status' => 'shipped',
                'purchased_at' => now()->subDays(5),
                'items' => [
                    ['wine' => $wines->random(), 'quantity' => 3],
                ],
            ],
            [
                'note' => "Name: John Doe\nPhone: +43 123 456 789\nStreet: 789 Vineyard Road\nCity: Graz\nPostal Code: 8010\nCountry: Austria",
                'status' => 'shipped',
                'purchased_at' => now()->subDays(4),
                'items' => [
                    ['wine' => $wines->random(), 'quantity' => 6],
                    ['wine' => $wines->random(), 'quantity' => 3],
                ],
            ],
            [
                'note' => "Name: John Doe\nPhone: +43 123 456 789\nStreet: 321 Cellar Lane\nCity: Linz\nPostal Code: 4020\nCountry: Austria",
                'status' => 'shipped',
                'purchased_at' => now()->subDays(3),
                'items' => [
                    ['wine' => $wines->random(), 'quantity' => 1],
                ],
            ],
            [
                'note' => "Name: John Doe\nPhone: +43 123 456 789\nStreet: 654 Barrel Street\nCity: Innsbruck\nPostal Code: 6020\nCountry: Austria",
                'status' => 'shipped',
                'purchased_at' => now()->subDays(2),
                'items' => [
                    ['wine' => $wines->random(), 'quantity' => 12],
                ],
            ],
            [
                'note' => "Name: John Doe\nPhone: +43 123 456 789\nStreet: 987 Cork Boulevard\nCity: Klagenfurt\nPostal Code: 9020\nCountry: Austria",
                'status' => 'completed',
                'purchased_at' => now()->subDays(1),
                'items' => [
                    ['wine' => $wines->random(), 'quantity' => 2],
                    ['wine' => $wines->random(), 'quantity' => 2],
                    ['wine' => $wines->random(), 'quantity' => 2],
                ],
            ],
        ];

        foreach ($orders as $order) {
            $items = $order['items'];
            $primaryWine = $items[0]['wine'] ?? null;

            $totalAmount = collect($items)->sum('quantity');
            $totalPrice = collect($items)->sum(fn ($item) => $item['quantity'] * $item['wine']->price_per_bottle);

            $purchase = Purchase::create([
                'user_id' => $customer->id,
                'wine_id' => $primaryWine?->id,
                'amount' => $totalAmount,
                'price' => $totalPrice,
                'status' => $order['status'],
                'purchased_at' => $order['purchased_at'],
                'note' => $order['note'],
            ]);

            foreach ($items as $item) {
                $wine = $item['wine'];

                if (! $wine) {
                    continue;
                }

                PurchaseItem::create([
                    'purchase_id' => $purchase->id,
                    'wine_id' => $wine->id,
                    'quantity' => $item['quantity'],
                    'unit_price' => $wine->price_per_bottle,
                    'line_total' => round($item['quantity'] * $wine->price_per_bottle, 2),
                ]);
            }
        }

        if ($this->command) {
            $this->command->info('✓ Created ' . count($orders) . ' purchase orders');
        }
    }
}
