<?php
declare(strict_types=1);

namespace App\Modules\Shipments;

use PDO;

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

    /**
     * @param array<string, mixed> $data
     */
    public function create(array $data): int
    {
        $statement = $this->pdo->prepare(
            'INSERT INTO shipment_packages (
                order_id, provider, delivery_method_id, credentials_id, command_id,
                status, carrier_id, package_type, weight_kg, length_cm, width_cm, height_cm,
                insurance_amount, insurance_currency, cod_amount, cod_currency,
                label_format, receiver_point_id, sender_point_id, reference_number, payload_json
            ) VALUES (
                :order_id, :provider, :delivery_method_id, :credentials_id, :command_id,
                :status, :carrier_id, :package_type, :weight_kg, :length_cm, :width_cm, :height_cm,
                :insurance_amount, :insurance_currency, :cod_amount, :cod_currency,
                :label_format, :receiver_point_id, :sender_point_id, :reference_number, :payload_json
            )'
        );

        $statement->execute([
            'order_id' => (int) ($data['order_id'] ?? 0),
            'provider' => trim((string) ($data['provider'] ?? 'allegro_wza')),
            'delivery_method_id' => $this->nullStr((string) ($data['delivery_method_id'] ?? '')),
            'credentials_id' => $this->nullStr((string) ($data['credentials_id'] ?? '')),
            'command_id' => $this->nullStr((string) ($data['command_id'] ?? '')),
            'status' => trim((string) ($data['status'] ?? 'draft')),
            'carrier_id' => $this->nullStr((string) ($data['carrier_id'] ?? '')),
            'package_type' => trim((string) ($data['package_type'] ?? 'PACKAGE')),
            'weight_kg' => isset($data['weight_kg']) ? (float) $data['weight_kg'] : null,
            'length_cm' => isset($data['length_cm']) ? (float) $data['length_cm'] : null,
            'width_cm' => isset($data['width_cm']) ? (float) $data['width_cm'] : null,
            'height_cm' => isset($data['height_cm']) ? (float) $data['height_cm'] : null,
            'insurance_amount' => isset($data['insurance_amount']) ? (float) $data['insurance_amount'] : null,
            'insurance_currency' => $this->nullStr((string) ($data['insurance_currency'] ?? '')),
            'cod_amount' => isset($data['cod_amount']) ? (float) $data['cod_amount'] : null,
            'cod_currency' => $this->nullStr((string) ($data['cod_currency'] ?? '')),
            'label_format' => trim((string) ($data['label_format'] ?? 'PDF')),
            'receiver_point_id' => $this->nullStr((string) ($data['receiver_point_id'] ?? '')),
            'sender_point_id' => $this->nullStr((string) ($data['sender_point_id'] ?? '')),
            'reference_number' => $this->nullStr((string) ($data['reference_number'] ?? '')),
            'payload_json' => isset($data['payload_json']) ? json_encode($data['payload_json'], JSON_UNESCAPED_UNICODE) : null,
        ]);

        return (int) $this->pdo->lastInsertId();
    }

    /**
     * @param array<string, mixed> $data
     */
    public function update(int $id, array $data): void
    {
        $sets = [];
        $params = ['id' => $id];

        $allowedFields = [
            'shipment_id', 'tracking_number', 'status', 'command_id',
            'label_path', 'error_message', 'delivery_status', 'delivery_status_raw',
        ];

        foreach ($allowedFields as $field) {
            if (array_key_exists($field, $data)) {
                $sets[] = "$field = :$field";
                $params[$field] = $data[$field];
            }
        }

        if (array_key_exists('payload_json', $data)) {
            $sets[] = 'payload_json = :payload_json';
            $params['payload_json'] = is_array($data['payload_json'])
                ? json_encode($data['payload_json'], JSON_UNESCAPED_UNICODE)
                : $data['payload_json'];
        }

        if ($sets === []) {
            return;
        }

        $sets[] = 'updated_at = NOW()';
        $sql = 'UPDATE shipment_packages SET ' . implode(', ', $sets) . ' WHERE id = :id';
        $statement = $this->pdo->prepare($sql);
        $statement->execute($params);
    }

    /**
     * @return array<string, mixed>|null
     */
    public function findById(int $id): ?array
    {
        $statement = $this->pdo->prepare('SELECT * FROM shipment_packages WHERE id = :id LIMIT 1');
        $statement->execute(['id' => $id]);
        $row = $statement->fetch(PDO::FETCH_ASSOC);
        return is_array($row) ? $row : null;
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public function findByOrderId(int $orderId): array
    {
        $statement = $this->pdo->prepare(
            'SELECT * FROM shipment_packages WHERE order_id = :order_id ORDER BY created_at DESC'
        );
        $statement->execute(['order_id' => $orderId]);
        return $statement->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    /**
     * @return array<string, mixed>|null
     */
    public function findLatestByOrderId(int $orderId): ?array
    {
        $statement = $this->pdo->prepare(
            'SELECT * FROM shipment_packages WHERE order_id = :order_id ORDER BY created_at DESC, id DESC LIMIT 1'
        );
        $statement->execute(['order_id' => $orderId]);
        $row = $statement->fetch(PDO::FETCH_ASSOC);

        return is_array($row) ? $row : null;
    }

    /**
     * @return array<string, mixed>|null
     */
    public function createManual(int $orderId, string $trackingNumber, ?string $carrierName = null): int
    {
        $statement = $this->pdo->prepare(
            'INSERT INTO shipment_packages (order_id, provider, tracking_number, carrier_id, status)
             VALUES (:order_id, :provider, :tracking_number, :carrier_id, :status)'
        );

        $statement->execute([
            'order_id' => $orderId,
            'provider' => 'manual',
            'tracking_number' => $trackingNumber,
            'carrier_id' => $carrierName !== null && trim($carrierName) !== '' ? trim($carrierName) : null,
            'status' => 'created',
        ]);

        return (int) $this->pdo->lastInsertId();
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public function findActiveForTracking(): array
    {
        $statement = $this->pdo->prepare(
            "SELECT * FROM shipment_packages
             WHERE provider != 'manual'
               AND delivery_status NOT IN ('delivered', 'returned', 'cancelled')
               AND status IN ('created', 'label_ready')
             ORDER BY delivery_status_updated_at ASC
             LIMIT 50"
        );
        $statement->execute();
        return $statement->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }

    public function updateDeliveryStatus(int $id, string $deliveryStatus, ?string $deliveryStatusRaw): void
    {
        $statement = $this->pdo->prepare(
            'UPDATE shipment_packages
             SET delivery_status = :delivery_status,
                 delivery_status_raw = :delivery_status_raw,
                 delivery_status_updated_at = NOW(),
                 updated_at = NOW()
             WHERE id = :id'
        );
        $statement->execute([
            'id' => $id,
            'delivery_status' => $deliveryStatus,
            'delivery_status_raw' => $deliveryStatusRaw,
        ]);
    }

    public function findByCommandId(string $commandId): ?array
    {
        $statement = $this->pdo->prepare('SELECT * FROM shipment_packages WHERE command_id = :command_id LIMIT 1');
        $statement->execute(['command_id' => $commandId]);
        $row = $statement->fetch(PDO::FETCH_ASSOC);
        return is_array($row) ? $row : null;
    }

    public function resolveCarrierName(string $provider, string $serviceId): ?string
    {
        if ($serviceId === '') {
            return null;
        }

        $statement = $this->pdo->prepare(
            'SELECT provider_service_name FROM carrier_delivery_method_mappings
             WHERE provider = :provider AND provider_service_id = :service_id
             LIMIT 1'
        );
        $statement->execute(['provider' => $provider, 'service_id' => $serviceId]);
        $row = $statement->fetch(PDO::FETCH_ASSOC);
        $name = trim((string) ($row['provider_service_name'] ?? ''));

        return $name !== '' ? $name : null;
    }

    private function nullStr(string $value): ?string
    {
        $trimmed = trim($value);
        return $trimmed === '' ? null : $trimmed;
    }
}
