<?php

namespace App\DataFixes;

use App\Enums\PriceType;
use App\Enums\ProductStockQuality;
use App\Models\OrderItem;

class FixOrderItemsUnitPrice extends BaseDataFix
{
    public function key(): string
    {
        return 'order-items-unit-price';
    }

    public function description(): string
    {
        return 'Fix order_items with unit_price = 0 (lookup correct price from product_prices)';
    }

    public function fix(): array
    {
        $items = OrderItem::where('unit_price', 0)
            ->with(['order', 'productVariant.productPrices'])
            ->get();

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

        foreach ($items as $item) {
            $order = $item->order;
            if (! $order) {
                $skipped++;

                continue;
            }

            $priceType = $this->resolvePriceType($order->price_type->value, $item->stock_quality->value);
            $productPrices = $item->productVariant?->productPrices;

            if (! $productPrices) {
                $notFound++;
                $details[] = [
                    'Order' => $order->order_number,
                    'Variant' => $item->product_variant_id,
                    'Qty' => $item->quantity,
                    'Old Price' => 0,
                    'New Price' => 'N/A',
                    'Status' => 'No prices found',
                ];

                continue;
            }

            $correctPrice = $productPrices->firstWhere('type', $priceType);

            if (! $correctPrice || $correctPrice->price <= 0) {
                $notFound++;
                $details[] = [
                    'Order' => $order->order_number,
                    'Variant' => $item->product_variant_id,
                    'Qty' => $item->quantity,
                    'Old Price' => 0,
                    'New Price' => 'N/A',
                    'Status' => "No {$priceType} price",
                ];

                continue;
            }

            $newSubtotal = $correctPrice->price * $item->quantity;

            $item->update([
                'unit_price' => $correctPrice->price,
                'subtotal' => $newSubtotal,
            ]);

            $details[] = [
                'Order' => $order->order_number,
                'Variant' => $item->product_variant_id,
                'Qty' => $item->quantity,
                'Old Price' => 0,
                'New Price' => number_format($correctPrice->price),
                'Status' => 'Fixed',
            ];

            $fixed++;
        }

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

        return [
            'fixed' => $fixed,
            'skipped' => $skipped,
            'not_found' => $notFound,
            'total' => $items->count(),
        ];
    }

    private function resolvePriceType(string $orderPriceType, string $stockQuality): string
    {
        if ($stockQuality === ProductStockQuality::REJECT->value) {
            return PriceType::REJECT->value;
        }

        $map = [
            PriceType::DISTRIBUTOR->value => PriceType::DISTRIBUTOR->value,
            PriceType::AGEN->value => PriceType::AGEN->value,
            PriceType::SUB_AGEN->value => PriceType::SUB_AGEN->value,
            PriceType::WHOLESALE->value => PriceType::WHOLESALE->value,
            PriceType::RETAIL->value => PriceType::RETAIL->value,
            PriceType::TIKTOK->value => PriceType::TIKTOK->value,
            PriceType::SHOPEE->value => PriceType::SHOPEE->value,
        ];

        return $map[$orderPriceType] ?? PriceType::RETAIL->value;
    }
}
