<?php

namespace App\Support\CostOfSale;

use App\Models\ClientDomain;
use App\Models\ClientProduct;
use App\Models\Product;
use App\Models\Tld;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

// PRC-816 — Bağlı satış varlığı için KATALOG referans maliyeti (ServiceCost/
// DomainCost, pricing tablosundan). Yalnız OKUR — gidere kopyalamaz (çift-kaynak yok).
class CostOfSaleReference
{
    /**
     * @return array{amount: float, time: string, currency_id: ?int}|null
     */
    public static function for(?Model $model): ?array
    {
        if (! $model) {
            return null;
        }

        [$productId, $tldId] = self::resolveProductOrTld($model);

        if ($productId) {
            return self::productCost((int) $productId);
        }
        if ($tldId) {
            return self::domainCost((int) $tldId);
        }

        return null;
    }

    /** @return array{0: int|null, 1: int|null} [product_id, tld_id] */
    private static function resolveProductOrTld(Model $model): array
    {
        return match (true) {
            $model instanceof Product => [$model->id, null],
            $model instanceof Tld => [null, $model->id],
            $model instanceof ClientProduct => [$model->product_id, null],
            $model instanceof ClientDomain => [null, $model->tld_id],
            // Order: birden çok kalem içerebilir → tek referans maliyet yok.
            default => [null, null],
        };
    }

    private static function productCost(int $productId): ?array
    {
        $row = DB::table('pricing')
            ->join('service_costs', 'pricing.relation_id', '=', 'service_costs.id')
            ->where('pricing.type', 'product_cost')
            ->where('pricing.segment', 'cost')
            ->where('pricing.time', 'month')
            ->where('pricing.period', 1)
            ->where('service_costs.is_active', true)
            ->where('service_costs.product_id', $productId)
            ->select('pricing.amount', 'pricing.currency_id')
            ->orderBy('pricing.id')
            ->first();

        return $row ? ['amount' => (float) $row->amount, 'time' => 'month', 'currency_id' => $row->currency_id] : null;
    }

    private static function domainCost(int $tldId): ?array
    {
        $row = DB::table('pricing')
            ->join('domain_costs', 'pricing.relation_id', '=', 'domain_costs.id')
            ->where('pricing.type', 'domain_cost')
            ->where('pricing.segment', 'cost')
            ->where('pricing.time', 'year')
            ->where('pricing.period', 1)
            ->where('domain_costs.is_active', true)
            ->where('domain_costs.tld_id', $tldId)
            ->select('pricing.amount', 'pricing.currency_id')
            ->orderBy('pricing.id')
            ->first();

        return $row ? ['amount' => (float) $row->amount, 'time' => 'year', 'currency_id' => $row->currency_id] : null;
    }
}
