<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Order;
use App\Models\OrderFinancialSnapshot;

class OrderFinancialSnapshotSeeder extends Seeder
{
    public function run()
    {
        $this->command->info('Creating order financial snapshots...');
        
        $orders = Order::all();
        
        foreach ($orders as $order) {
            // Skip if snapshot already exists
            if ($order->financialSnapshot) {
                continue;
            }

            $platformCommissionRate = 0.15;
            $deliveryCommissionRate = 0.80;

            $customerPayment = $order->total;
            $platformCommission = $customerPayment * $platformCommissionRate;
            $deliveryBoyEarning = $order->delivery_fee * $deliveryCommissionRate;
            $restaurantEarning = $customerPayment - $platformCommission - $deliveryBoyEarning;

            $isImmutable = $order->status === 'delivered';
            $refundAmount = $isImmutable && rand(0, 100) < 10 ? rand(100, 500) : 0; // 10% chance of refund

            OrderFinancialSnapshot::create([
                'order_id' => $order->id,
                'customer_payment' => $customerPayment,
                'platform_commission' => $platformCommission,
                'restaurant_earning' => $restaurantEarning - $refundAmount,
                'delivery_boy_earning' => $deliveryBoyEarning,
                'refund_amount' => $refundAmount,
                'settlement_status' => $isImmutable ? 'settled' : 'pending',
                'snapshot_created_at' => $order->created_at,
                'is_immutable' => $isImmutable
            ]);
        }
        
        $this->command->info('Order financial snapshots created successfully!');
    }
}