<?php

namespace App\Http\Controllers;

use App\Http\Requests\UpdateUserDealershipsRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mtc\MercuryDataModels\Dealership;
use Mtc\MercuryDataModels\User;

class UserDealershipController extends Controller
{
    public function __construct()
    {
        $this->middleware([
            'permission:manage-site-users',
        ]);
    }

    /**
     * Get user's current dealership assignments and all available dealerships.
     */
    public function show(Request $request, int $userId): JsonResponse
    {
        $this->validateUserBelongsToTenant($userId);

        $dealershipIds = DB::table('user_dealerships')
            ->where('user_id', $userId)
            ->pluck('dealership_id')
            ->toArray();

        $dealerships = Dealership::select(['id', 'name'])
            ->orderBy('name')
            ->get();

        return response()->json([
            'dealership_ids' => $dealershipIds,
            'dealerships' => $dealerships,
        ]);
    }

    /**
     * Sync user's dealership assignments.
     */
    public function update(UpdateUserDealershipsRequest $request, int $userId): JsonResponse
    {
        $this->validateUserBelongsToTenant($userId);

        $dealershipIds = $request->input('dealership_ids', []);

        DB::transaction(function () use ($userId, $dealershipIds) {
            DB::table('user_dealerships')
                ->where('user_id', $userId)
                ->delete();

            if (!empty($dealershipIds)) {
                $rows = array_map(fn($id) => [
                    'user_id' => $userId,
                    'dealership_id' => $id,
                ], $dealershipIds);

                DB::table('user_dealerships')->insert($rows);
            }
        });

        return response()->json([
            'message' => 'User dealership access updated successfully.',
            'dealership_ids' => $dealershipIds,
        ]);
    }

    /**
     * Validate that the given user belongs to the current tenant.
     */
    private function validateUserBelongsToTenant(int $userId): void
    {
        $user = User::findOrFail($userId);

        $belongsToTenant = $user->tenants()
            ->where('tenant_id', tenant('id'))
            ->exists();

        if (!$belongsToTenant) {
            abort(404, 'User not found on this site.');
        }
    }
}
