<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreVehicleSubscriptionRequest;
use Illuminate\Http\JsonResponse;
use Mtc\Crm\Traits\RetrievesCustomerId;
use Mtc\MercuryDataModels\Enums\VehicleSubscriptionEventType;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleSubscription;

class VehicleSubscriptionController extends Controller
{
    use RetrievesCustomerId;

    public function store(StoreVehicleSubscriptionRequest $request, Vehicle $vehicle): JsonResponse
    {
        // Get or create customer
        $customerId = $this->getCustomerId(
            $request->input('email'),
            array_filter([
                'first_name' => $request->input('first_name'),
                'last_name' => $request->input('last_name'),
            ])
        );

        if (!$customerId) {
            return response()->json([
                'success' => false,
                'message' => __('vehicle_subscriptions.unable_to_process'),
            ], 500);
        }

        $eventTypes = $request->input('event_types');
        $subscriptionsCreated = 0;

        foreach ($eventTypes as $eventType) {
            VehicleSubscription::query()->firstOrCreate([
                'customer_id' => $customerId,
                'vehicle_id' => $vehicle->id,
                'event_type' => $eventType,
            ]);
            $subscriptionsCreated++;
        }

        return response()->json([
            'success' => true,
            'message' => __('vehicle_subscriptions.subscribed_success'),
            'subscriptions' => $subscriptionsCreated,
        ]);
    }

    public function unsubscribe(string $token): JsonResponse
    {
        $subscription = VehicleSubscription::query()
            ->where('unsubscribe_token', $token)
            ->first();

        if (!$subscription) {
            return response()->json([
                'success' => false,
                'message' => __('vehicle_subscriptions.subscription_not_found'),
            ], 404);
        }

        $subscription->delete();

        return response()->json([
            'success' => true,
            'message' => __('vehicle_subscriptions.unsubscribed_success'),
        ]);
    }

    public function unsubscribeAll(string $token): JsonResponse
    {
        $subscription = VehicleSubscription::query()
            ->where('unsubscribe_token', $token)
            ->first();

        if (!$subscription) {
            return response()->json([
                'success' => false,
                'message' => __('vehicle_subscriptions.subscription_not_found'),
            ], 404);
        }

        // Delete all subscriptions for this customer
        VehicleSubscription::query()
            ->where('customer_id', $subscription->customer_id)
            ->delete();

        return response()->json([
            'success' => true,
            'message' => __('vehicle_subscriptions.unsubscribed_all_success'),
        ]);
    }
}
