<?php

namespace App\Pix;

class PixStatusStorage
{
    public static function getStorageDir(): string
    {
        $dir = __DIR__ . '/../../storage';
        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        return $dir;
    }

    public static function getFilePath(string $txid): string
    {
        return self::getStorageDir() . '/pix-status-' . md5((string) $txid) . '.json';
    }

    public static function save(string $txid, string $status, array $extra = []): array
    {
        $data = [
            'txid' => $txid,
            'status' => $status,
            'updated_at' => date('c'),
        ];

        if (!empty($extra)) {
            $data['extra'] = $extra;
        }

        $file = self::getFilePath($txid);
        $dir = self::getStorageDir();

        if (!is_dir($dir)) {
            mkdir($dir, 0755, true);
        }

        file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        return $data;
    }

    public static function load(string $txid): ?array
    {
        $file = self::getFilePath($txid);

        if (!is_file($file)) {
            return null;
        }

        $content = file_get_contents($file);
        if ($content === false) {
            return null;
        }

        $data = json_decode($content, true);
        return is_array($data) ? $data : null;
    }

    public static function normalizeStatus($payload): string
    {
        if (!is_array($payload)) {
            return 'pendente';
        }

        $status = null;
        if (isset($payload['status'])) {
            $status = $payload['status'];
        } elseif (isset($payload['pix'][0]['status'])) {
            $status = $payload['pix'][0]['status'];
        } elseif (isset($payload['data']['status'])) {
            $status = $payload['data']['status'];
        } elseif (isset($payload['event']) && isset($payload['event']['status'])) {
            $status = $payload['event']['status'];
        } elseif (isset($payload['payload']['status'])) {
            $status = $payload['payload']['status'];
        }

        if (is_string($status)) {
            $statusUpper = strtoupper($status);
            if ($statusUpper === 'CONCLUIDA' || $statusUpper === 'PAGO' || $statusUpper === 'PAID' || $statusUpper === 'SUCCESS' || $statusUpper === 'OK') {
                return 'pago';
            }
            if ($statusUpper === 'REMOVIDA_PELO_USUARIO_RECEBEDOR' || $statusUpper === 'CANCELADA' || $statusUpper === 'CANCELADO' || $statusUpper === 'CANCELLED') {
                return 'cancelado';
            }
            if ($statusUpper === 'ATIVA' || $statusUpper === 'PENDENTE' || $statusUpper === 'PENDING' || $statusUpper === 'ATIVA') {
                return 'pendente';
            }
        }

        if (is_array($payload['pix'] ?? null) && !empty($payload['pix'])) {
            $pixItem = $payload['pix'][0] ?? [];
            if (is_array($pixItem) && (!empty($pixItem['txid']) || !empty($pixItem['endToEndId'])) && (!empty($pixItem['valor']) || isset($pixItem['valor']))) {
                return 'pago';
            }
        }

        return 'pendente';
    }

    public static function extractTxid($payload): ?string
    {
        if (!is_array($payload)) {
            return null;
        }

        $candidates = [
            $payload['txid'] ?? null,
            $payload['data']['txid'] ?? null,
            $payload['data']['endToEndId'] ?? null,
            $payload['pix'][0]['txid'] ?? null,
            $payload['pix'][0]['endToEndId'] ?? null,
            $payload['pix'][0]['id'] ?? null,
            $payload['event']['txid'] ?? null,
            $payload['payload']['txid'] ?? null,
            $payload['payload']['endToEndId'] ?? null,
        ];

        foreach ($candidates as $candidate) {
            if (is_string($candidate) && trim($candidate) !== '') {
                return $candidate;
            }
        }

        return null;
    }
}
