<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Order;
use App\Models\Product;
use App\Models\Project;

class ProjectFromOrderService
{
    public function createFromOrder(Order $order): ?Project
    {
        if ($order->project_id) {
            return $order->project;
        }

        $order->loadMissing('product');
        $product = $order->product;

        if (! $product instanceof Product) {
            return null;
        }

        $project = Project::create($this->buildProjectAttributes($order, $product));

        $order->update(['project_id' => $project->id]);

        return $project;
    }

    /**
     * @return array<string, mixed>
     */
    private function buildProjectAttributes(Order $order, Product $product): array
    {
        $images = array_values(array_filter([
            $product->image,
            ...($product->gallery ?? []),
        ]));

        return [
            'name' => $product->name,
            'excerpt' => $product->excerpt,
            'desc' => $product->desc,
            'user_id' => $order->user_id,
            'producer_id' => $product->producer_id ?? $order->producer_id,
            'category_id' => $product->category_id,
            'breed_id' => $product->breed_id,
            'product_id' => $product->id,
            'quantity' => $order->quantity,
            'unit' => $this->normalizeUnit($order->unit ?? $product->unit),
            'unit_price' => $order->unit_price,
            'budget' => $order->total_price,
            'province_id' => $order->province_id ?? $product->province_id,
            'county_id' => $order->county_id ?? $product->county_id,
            'address' => $order->delivery_address ?? $product->address,
            'images' => $images !== [] ? $images : null,
            'notes' => 'ایجاد خودکار از سفارش ' . $order->order_number,
            'status' => Project::STATUS_UNSIGNED,
            'sale_registration_enabled' => true,
            'created_by' => $order->user_id,
            'updated_by' => $order->user_id,
        ];
    }

    private function normalizeUnit(?string $unit): ?string
    {
        if ($unit === null || $unit === '') {
            return null;
        }

        if (in_array($unit, array_keys(Project::unitOptions()), true)) {
            return $unit;
        }

        return match (true) {
            in_array($unit, ['راس', 'head'], true) => Project::UNIT_HEAD,
            in_array($unit, ['تعداد', 'عدد', 'count'], true) => Project::UNIT_COUNT,
            in_array($unit, ['وزن', 'کیلو', 'kg', 'weight'], true) => Project::UNIT_WEIGHT,
            default => Project::UNIT_COUNT,
        };
    }
}
