<?php

namespace App\Http\Controllers;

use Mtc\MercuryDataModels\Enums\VehicleSubscriptionEventType;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleSubscription;

class VehicleSubscriptionController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = VehicleSubscription::query()
            ->with(['vehicle', 'customer'])
            ->orderBy('created_at', 'desc');

        if ($request->has('vehicle_id')) {
            $query->where('vehicle_id', $request->input('vehicle_id'));
        }

        if ($request->has('customer_id')) {
            $query->where('customer_id', $request->input('customer_id'));
        }

        if ($request->has('event_type')) {
            $query->where('event_type', $request->input('event_type'));
        }

        $subscriptions = $query->paginate($request->input('per_page', 50));

        return response()->json([
            'data' => $subscriptions->items(),
            'meta' => [
                'current_page' => $subscriptions->currentPage(),
                'last_page' => $subscriptions->lastPage(),
                'per_page' => $subscriptions->perPage(),
                'total' => $subscriptions->total(),
            ],
        ]);
    }

    /**
     * Get vehicles grouped by subscription count, ordered by popularity.
     * Excludes soft-deleted vehicles.
     */
    public function groupedByVehicle(Request $request): JsonResponse
    {
        $query = Vehicle::query()
            ->whereNull('deleted_at')
            ->whereHas('subscriptions')
            ->withCount([
                'subscriptions',
                'subscriptions as unique_subscribers_count' => function ($query) {
                    $query->selectRaw('COUNT(DISTINCT customer_id)');
                },
            ])
            ->with(['make', 'model'])
            ->orderByDesc('subscriptions_count');

        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('title', 'like', "%{$search}%")
                    ->orWhereHas('make', fn ($q) => $q->where('name', 'like', "%{$search}%"))
                    ->orWhereHas('model', fn ($q) => $q->where('name', 'like', "%{$search}%"));
            });
        }

        $vehicles = $query->paginate($request->input('per_page', 50));

        $data = collect($vehicles->items())->map(function ($vehicle) {
            return [
                'id' => $vehicle->id,
                'title' => $vehicle->title,
                'make' => $vehicle->make?->name,
                'model' => $vehicle->model?->name,
                'year' => $vehicle->year,
                'price' => $vehicle->price,
                'subscriptions_count' => $vehicle->subscriptions_count,
                'unique_subscribers_count' => $vehicle->unique_subscribers_count,
            ];
        });

        return response()->json([
            'data' => $data,
            'meta' => [
                'current_page' => $vehicles->currentPage(),
                'last_page' => $vehicles->lastPage(),
                'per_page' => $vehicles->perPage(),
                'total' => $vehicles->total(),
            ],
        ]);
    }

    public function forVehicle(Vehicle $vehicle): JsonResponse
    {
        $subscriptions = $vehicle->subscriptions()
            ->with(['customer', 'vehicle'])
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json([
            'data' => $subscriptions,
            'count' => $subscriptions->count(),
            'vehicle' => [
                'id' => $vehicle->id,
                'title' => $vehicle->title,
            ],
        ]);
    }

    public function stats(): JsonResponse
    {
        return response()->json([
            'total_subscriptions' => VehicleSubscription::count(),
            'by_event_type' => VehicleSubscription::query()
                ->selectRaw('event_type, COUNT(*) as count')
                ->groupBy('event_type')
                ->pluck('count', 'event_type'),
            'unique_vehicles' => VehicleSubscription::distinct('vehicle_id')->count('vehicle_id'),
            'unique_customers' => VehicleSubscription::distinct('customer_id')->count('customer_id'),
        ]);
    }

    public function eventTypes(): JsonResponse
    {
        $types = collect(VehicleSubscriptionEventType::cases())
            ->map(fn($type) => [
                'value' => $type->value,
                'label' => $type->label(),
            ]);

        return response()->json([
            'data' => $types,
        ]);
    }

    public function destroy(VehicleSubscription $subscription): JsonResponse
    {
        $subscription->delete();

        return response()->json([
            'success' => true,
            'message' => 'Subscription deleted successfully',
        ]);
    }
}
