<?php

declare(strict_types=1);

namespace App\Modules\Parties\Application\Services;

use App\Shared\Schema\PartySchemaSupport;
use PDO;

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

    public function ensureSchema(): void
    {
        PartySchemaSupport::ensurePartiesSchema($this->pdo);
    }

    public function load(int $id): ?array
    {
        if ($id <= 0) {
            return null;
        }
        $statement = $this->pdo->prepare('SELECT * FROM parties WHERE id=? LIMIT 1');
        $statement->execute([$id]);
        $party = $statement->fetch() ?: null;
        if (!$party) {
            return null;
        }

        $isSupplierOnly = ((int)($party['is_supplier'] ?? 0) === 1) && ((int)($party['is_customer'] ?? 0) !== 1);
        $isCustomerOnly = ((int)($party['is_customer'] ?? 0) === 1) && ((int)($party['is_supplier'] ?? 0) !== 1);
        $type = $isSupplierOnly ? 'supplier' : ($isCustomerOnly ? 'customer' : 'all');
        $backUrl = $type === 'customer' ? '/parties/customers' : ($type === 'supplier' ? '/parties/suppliers' : '/parties');
        $editUrl = $backUrl . '?edit=' . $id;

        return [
            'party' => $party,
            'back_url' => $backUrl,
            'edit_url' => $editUrl,
        ];
    }
}
