<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Master\Models\AutoTraderAdvertiser;
use App\Services\AutoTraderAdvertisersApi;
use Illuminate\Http\JsonResponse;
use Mtc\MercuryDataModels\Dealership;

class AutoTraderAccessController extends Controller
{
    public function __construct(
        protected AutoTraderAdvertisersApi $api
    ) {
        $this->middleware(['permission:manage-settings']);
    }

    public function index(): JsonResponse
    {
        $masterAdvertiserId = Settings::get('auto-trader-advertiser-id');

        $dealerships = Dealership::all()
            ->map(fn(Dealership $dealership) => [
                'id' => $dealership->id,
                'name' => $dealership->name,
                'auto_trader_id' => $dealership->data['auto-trader-location-id'] ?? null,
            ])
            ->filter(fn($d) => !empty($d['auto_trader_id']));

        $uniqueIds = $dealerships->pluck('auto_trader_id')->unique()->values();

        if ($masterAdvertiserId && !$uniqueIds->contains($masterAdvertiserId)) {
            $uniqueIds->push($masterAdvertiserId);
        }

        if ($uniqueIds->isEmpty()) {
            return response()->json([
                'success' => true,
                'master_advertiser_id' => $masterAdvertiserId,
                'master_accessible' => null,
                'summary' => [
                    'total_dealer_ids' => 0,
                    'accessible' => 0,
                    'not_accessible' => 0,
                ],
                'results' => [],
            ]);
        }

        $cached = AutoTraderAdvertiser::whereIn('advertiser_id', $uniqueIds)
            ->get()
            ->keyBy('advertiser_id');

        $uncachedIds = $uniqueIds->diff($cached->keys())->values()->all();

        if (!empty($uncachedIds)) {
            $apiResult = $this->api->getAdvertisersByIds($uncachedIds);

            if ($apiResult['success']) {
                foreach ($apiResult['advertisers'] ?? [] as $advertiserData) {
                    $model = AutoTraderAdvertiser::upsertFromApiResponse($advertiserData);
                    $cached->put($model->advertiser_id, $model);
                }
            }
        }

        $grouped = [];

        if ($masterAdvertiserId) {
            $grouped[$masterAdvertiserId] = [
                'auto_trader_id' => $masterAdvertiserId,
                'is_master' => true,
                'dealerships' => [],
            ];
        }

        foreach ($dealerships as $dealership) {
            $atId = $dealership['auto_trader_id'];
            if (!isset($grouped[$atId])) {
                $grouped[$atId] = [
                    'auto_trader_id' => $atId,
                    'is_master' => false,
                    'dealerships' => [],
                ];
            }
            $grouped[$atId]['dealerships'][] = $dealership['name'];
        }

        $results = collect($grouped)->map(function ($entry) use ($cached) {
            $advertiser = $cached->get($entry['auto_trader_id']);

            return [
                'auto_trader_id' => $entry['auto_trader_id'],
                'is_master' => $entry['is_master'],
                'dealerships' => $entry['dealerships'],
                'accessible' => $advertiser !== null,
                'advertiser' => $advertiser?->toApiFormat(),
            ];
        })->values()->all();

        $accessibleCount = collect($results)->where('accessible', true)->count();

        return response()->json([
            'success' => true,
            'summary' => [
                'total' => count($results),
                'accessible' => $accessibleCount,
                'not_accessible' => count($results) - $accessibleCount,
            ],
            'results' => $results,
        ]);
    }
}
