<?php

namespace Database\Seeders;

use App\Models\Product;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\User;
use App\Services\ProfitService;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class ProfitTestDataSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        DB::beginTransaction();

        try {
            // Update some existing products with purchase prices for testing
            $products = Product::take(10)->get();
            
            foreach ($products as $index => $product) {
                $purchasePrice = $product->price * 0.6; // 40% margin
                $product->update(['purchase_price' => $purchasePrice]);
            }

            // Create a test order with profit data
            $user = User::first();
            if ($user && $products->count() > 0) {
                $order = Order::create([
                    'user_id' => $user->id,
                    'source' => 'online',
                    'address_snapshot' => [
                        'name' => 'Test User',
                        'phone' => '1234567890',
                        'address' => 'Test Address',
                        'city' => 'Test City',
                        'state' => 'Test State',
                        'pincode' => '123456'
                    ],
                    'subtotal' => 0,
                    'discount_total' => 10.00,
                    'shipping_total' => 50.00,
                    'total_payable' => 0,
                    'payment_status' => Order::PAYMENT_PAID,
                    'payment_method' => 'online',
                    'status' => Order::STATUS_DELIVERED,
                    'placed_at' => now()->subDays(5),
                ]);

                // Create order items with profit calculations
                $cartItems = [];
                $subtotal = 0;

                foreach ($products->take(3) as $product) {
                    $qty = rand(1, 3);
                    $price = $product->price;
                    $lineTotal = $qty * $price;
                    $subtotal += $lineTotal;

                    $cartItems[] = [
                        'product_id' => $product->id,
                        'qty' => $qty,
                        'price' => $price,
                    ];
                }

                // Update order totals
                $totalPayable = $subtotal - $order->discount_total + $order->shipping_total;
                $order->update([
                    'subtotal' => $subtotal,
                    'total_payable' => $totalPayable,
                ]);

                // Use ProfitService to create order items with profit calculations
                $profitService = new ProfitService();
                $profitService->allocateOrderCosts($order, $cartItems);

                $this->command->info("Created test order #{$order->id} with profit data");
            }

            DB::commit();
            $this->command->info('Profit test data seeded successfully!');

        } catch (\Exception $e) {
            DB::rollBack();
            $this->command->error('Failed to seed profit test data: ' . $e->getMessage());
        }
    }
}