<?php

declare(strict_types=1);

namespace App\Modules\Sales\Application\Services;

use App\Core\SchemaRuntime;
use App\Shared\Schema\QuotationSchemaSupport;
use App\Shared\Support\QuotationSupport;
use PDO;

final class QuotationPriceService
{
    public function __construct(private PDO $pdo)
    {
    }

    public function ensureSchema(): void
    {
        SchemaRuntime::ensure($this->pdo, 'quotations_schema', function (): void { QuotationSchemaSupport::ensureQuotationsSchema($this->pdo); }, 'sql/migrate_v1_26_quotations.sql');
    }

    public function resolve(int $itemId, int $partyId, string $invoiceDate): array
    {
        if ($itemId <= 0) {
            return ['ok' => false, 'message' => 'invalid_item'];
        }

        $statement = $this->pdo->prepare('SELECT id, name, price FROM items WHERE id=? LIMIT 1');
        $statement->execute([$itemId]);
        $item = $statement->fetch();
        if (!$item) {
            return ['ok' => false, 'message' => 'not_found'];
        }

        $basePrice = (float) $item['price'];
        $quote = $partyId > 0 ? QuotationSupport::effectivePrice($this->pdo, $partyId, $itemId, $invoiceDate) : null;

        return [
            'ok' => true,
            'item_id' => $itemId,
            'item_name' => (string) $item['name'],
            'base_price' => $basePrice,
            'price' => $quote ? (float) $quote['unit_price'] : $basePrice,
            'from_quotation' => $quote ? true : false,
            'quotation_id' => $quote['quotation_id'] ?? null,
            'quotation_no' => $quote['quotation_no'] ?? null,
            'valid_until' => $quote['valid_until'] ?? null,
        ];
    }
}
