<?php

namespace App\DataFixes;

use App\Models\Order;

class FixOrdersCogs extends BaseDataFix
{
    public function key(): string
    {
        return 'orders-cogs';
    }

    public function description(): string
    {
        return 'Fix COGS yang 0 (hitung dari capital price × quantity)';
    }

    public function fix(): array
    {
        $orders = Order::where('cogs', 0)
            ->where('status', '!=', 'cancelled')
            ->with(['orderItems.productVariant.productPrices'])
            ->get();

        $fixed = 0;
        $skipped = 0;
        $noItems = 0;
        $details = [];

        foreach ($orders as $order) {
            if ($order->orderItems->isEmpty()) {
                $noItems++;

                continue;
            }

            $totalCogs = 0;
            $hasValidCapital = true;

            foreach ($order->orderItems as $item) {
                $capitalPrice = $item->productVariant?->productPrices
                    ->firstWhere('type', 'capital');

                if (! $capitalPrice || $capitalPrice->price <= 0) {
                    $hasValidCapital = false;
                    break;
                }

                $totalCogs += $capitalPrice->price * $item->quantity;
            }

            if (! $hasValidCapital) {
                $skipped++;
                $details[] = [
                    'Order' => $order->order_number,
                    'Items' => $order->orderItems->count(),
                    'Old COGS' => '0',
                    'New COGS' => 'N/A',
                    'Status' => 'Missing capital price',
                ];

                continue;
            }

            if ($totalCogs === 0) {
                $skipped++;

                continue;
            }

            $order->update([
                'cogs' => $totalCogs,
            ]);

            $details[] = [
                'Order' => $order->order_number,
                'Items' => $order->orderItems->count(),
                'Old COGS' => '0',
                'New COGS' => number_format($totalCogs),
                'Status' => 'Fixed',
            ];

            $fixed++;
        }

        if (! empty($details)) {
            $this->command->newLine();
            $this->command->table(
                ['Order', 'Items', 'Old COGS', 'New COGS', 'Status'],
                $details
            );
        }

        return [
            'fixed' => $fixed,
            'skipped' => $skipped,
            'no_items' => $noItems,
            'total' => $orders->count(),
        ];
    }
}
