<?php

namespace App\DataFixes;

use App\Models\Cutting;

class FixCuttingsCost extends BaseDataFix
{
    public function key(): string
    {
        return 'cuttings-cost';
    }

    public function description(): string
    {
        return 'Recalculate total_material_cost and cost_per_unit for cuttings';
    }

    public function fix(): array
    {
        $cuttings = Cutting::with([
            'cuttingMaterials.rawMaterialPrice',
            'cuttingResults',
        ])->get();

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

        foreach ($cuttings as $cutting) {
            $oldTotal = $cutting->total_material_cost;
            $oldPerUnit = $cutting->cost_per_unit;

            $totalMaterialCost = 0;
            foreach ($cutting->cuttingMaterials as $material) {
                $price = $material->rawMaterialPrice;
                if ($price) {
                    $totalMaterialCost += $price->price * ($material->material_usage ?? 0);
                }
            }

            $cuttingResult = $cutting->cuttingResults->sum('cutting_result');
            $costPerUnit = 0;
            if ($cuttingResult > 0) {
                $costPerUnit = (int) ($totalMaterialCost / $cuttingResult);
            }

            if ($oldTotal === $totalMaterialCost && $oldPerUnit === $costPerUnit) {
                $skipped++;

                continue;
            }

            $cutting->update([
                'total_material_cost' => $totalMaterialCost,
                'cost_per_unit' => $costPerUnit,
            ]);

            $details[] = [
                'ID' => $cutting->id,
                'Description' => $cutting->description ?? '-',
                'Old Total' => number_format($oldTotal ?? 0),
                'New Total' => number_format($totalMaterialCost),
                'Old/Unit' => number_format($oldPerUnit ?? 0),
                'New/Unit' => number_format($costPerUnit),
            ];

            $fixed++;
        }

        if (! empty($details)) {
            $this->command->newLine();
            $this->command->table(
                ['ID', 'Description', 'Old Total', 'New Total', 'Old/Unit', 'New/Unit'],
                $details
            );
        }

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