<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'min:2'],
            'email' => ['required', 'email', Rule::unique('users', 'email')],
            'password' => ['required', 'string', 'min:6'],
            'role' => ['nullable', Rule::in(['agent', 'user'])],
            'organization' => ['required', 'string'],
            'department' => ['nullable', 'string'],
            'category' => ['nullable', 'string', Rule::exists('support_categories', 'name')],
        ]);

        $organization = $validated['organization'] ?? $validated['department'] ?? null;

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'role' => $validated['role'] ?? 'user',
            'department' => $organization,
            'category' => $validated['category'] ?? null,
        ]);

        $token = $user->createToken('auth-token')->plainTextToken;

        return response()
            ->json(['user' => $this->userPayload($user)], 201)
            ->cookie(
                'auth_token',
                $token,
                60 * 24 * 7, // 7 days
                '/',
                null,
                false, // secure
                true,  // httpOnly
                false,
                'Lax'
            );
    }

    public function login(Request $request)
    {
        $validated = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string', 'min:6'],
        ]);

        $user = User::where('email', $validated['email'])->first();
        if (!$user || !Hash::check($validated['password'], $user->password)) {
            return response()->json(['message' => 'Invalid credentials'], 401);
        }

        $user->tokens()->delete();
        $token = $user->createToken('auth-token')->plainTextToken;

        return response()
            ->json(['user' => $this->userPayload($user)])
            ->cookie(
                'auth_token',
                $token,
                60 * 24 * 7, // 7 days
                '/',
                null,
                false, // secure
                true,  // httpOnly
                false,
                'Lax'
            );
    }

    public function me(Request $request)
    {
        return response()->json($this->userPayload($request->user()->loadMissing('clientApiKey')));
    }

    public function logout(Request $request)
    {
        if ($request->user()) {
            $request->user()->currentAccessToken()->delete();
        }

        return response()
            ->json(['message' => 'Logged out successfully'])
            ->cookie('auth_token', '', -1, '/', null, false, true, false, 'Lax');
    }

    private function userPayload(User $user): array
    {
        $user->loadMissing('clientApiKey');

        return [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'role' => $user->supportDeskRole(),
            'is_super_admin' => $user->supportDeskIsSuperAdmin(),
            'isSuperAdmin' => $user->supportDeskIsSuperAdmin(),
            'organization' => $user->department,
            'department' => $user->department,
            'category' => $user->category,
            'created_at' => $user->created_at,
            'client_api_key_id' => $user->client_api_key_id,
            'client_integration' => $user->clientApiKey
                ? [
                    'id' => $user->clientApiKey->id,
                    'client_name' => $user->clientApiKey->client_name,
                    'features' => $user->clientApiKey->serviceFeatures(),
                ]
                : null,
        ];
    }
}
