<?php

namespace App\Services\Auction;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class GenericJapaneseAuctionProvider implements AuctionProviderInterface
{
    protected string $baseUrl;
    protected string $apiKey;
    protected string $apiSecret;

    public function __construct()
    {
        $this->baseUrl = config('services.japan_auction.url', env('JAPAN_AUCTION_API_URL', 'https://api.japan-auctions-example.com/v1'));
        $this->apiKey = config('services.japan_auction.key', env('JAPAN_AUCTION_API_KEY', ''));
        $this->apiSecret = config('services.japan_auction.secret', env('JAPAN_AUCTION_API_SECRET', ''));
    }

    protected function client()
    {
        return Http::baseUrl($this->baseUrl)
            ->withHeaders([
                'X-API-KEY' => $this->apiKey,
                'X-API-SECRET' => $this->apiSecret,
                'Accept' => 'application/json',
            ])
            ->timeout(15);
    }

    public function getLiveAuctions(array $filters = []): array
    {
        try {
            $response = $this->client()->get('/lots/live', $filters);
            if ($response->successful()) {
                return $response->json('data', []);
            }
        } catch (\Throwable $e) {
            Log::error('Japan Auction API getLiveAuctions failed: ' . $e->getMessage());
        }
        return [];
    }

    public function getAuctionVehicle(string $auctionId): ?array
    {
        try {
            $response = $this->client()->get("/lots/{$auctionId}");
            if ($response->successful()) {
                return $response->json('data');
            }
        } catch (\Throwable $e) {
            Log::error("Japan Auction API getAuctionVehicle {$auctionId} failed: " . $e->getMessage());
        }
        return null;
    }

    public function getAuctionSheet(string $auctionId): ?string
    {
        try {
            $response = $this->client()->get("/lots/{$auctionId}/sheet");
            if ($response->successful()) {
                return $response->json('sheet_url');
            }
        } catch (\Throwable $e) {
            Log::error("Japan Auction API getAuctionSheet {$auctionId} failed: " . $e->getMessage());
        }
        return null;
    }

    public function getAuctionHistory(string $chassisNumber): array
    {
        try {
            $response = $this->client()->get("/history/{$chassisNumber}");
            if ($response->successful()) {
                return $response->json('data', []);
            }
        } catch (\Throwable $e) {
            Log::error("Japan Auction API getAuctionHistory failed: " . $e->getMessage());
        }
        return [];
    }

    public function placeBid(string $auctionId, float $maxBidJpy, array $metadata = []): array
    {
        try {
            $response = $this->client()->post("/lots/{$auctionId}/bid", [
                'max_bid_jpy' => $maxBidJpy,
                'client_reference' => $metadata['bid_code'] ?? null,
                'timestamp' => now()->toISOString(),
            ]);

            if ($response->successful()) {
                return [
                    'success' => true,
                    'transaction_id' => $response->json('transaction_id'),
                    'status' => $response->json('status', 'SUBMITTED'),
                    'message' => $response->json('message', 'Bid submitted to Japan auction floor.'),
                ];
            }
        } catch (\Throwable $e) {
            Log::error("Japan Auction API placeBid {$auctionId} failed: " . $e->getMessage());
        }

        return [
            'success' => false,
            'message' => 'Failed to reach Japanese auction API gateway.',
        ];
    }

    public function cancelBid(string $bidExternalId): bool
    {
        try {
            $response = $this->client()->delete("/bids/{$bidExternalId}");
            return $response->successful();
        } catch (\Throwable $e) {
            Log::error("Japan Auction API cancelBid failed: " . $e->getMessage());
            return false;
        }
    }

    public function getBidStatus(string $bidExternalId): array
    {
        try {
            $response = $this->client()->get("/bids/{$bidExternalId}");
            return $response->json('data', []);
        } catch (\Throwable $e) {
            Log::error("Japan Auction API getBidStatus failed: " . $e->getMessage());
            return [];
        }
    }

    public function getAuctionResult(string $auctionId): array
    {
        try {
            $response = $this->client()->get("/lots/{$auctionId}/result");
            return $response->json('data', []);
        } catch (\Throwable $e) {
            Log::error("Japan Auction API getAuctionResult failed: " . $e->getMessage());
            return [];
        }
    }
}
