<?php

namespace App\Http\Controllers\Api\V1\Showroom;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\PosDevice;
use App\Models\ShowroomSession;
use App\Services\Showroom\ShowroomPermissionService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class AuthController extends Controller
{
    public function __construct(private readonly ShowroomPermissionService $permissionService)
    {
    }

    public function login(Request $request)
    {
        $data = $request->validate([
            'email' => 'required|email',
            'password' => 'required|string',
            'device_uid' => 'nullable|string|max:191',
            'device_name' => 'nullable|string|max:191',
            'showroom_id' => 'nullable|string|max:191',
        ]);

        $admin = Admin::with('role')->where('email', $data['email'])->first();
        if (! $admin || ! Hash::check($data['password'], (string) $admin->password)) {
            return response()->json(['message' => 'Invalid showroom login credentials.'], 401);
        }

        if ($admin->role && $admin->role->status === false) {
            return response()->json(['message' => 'This role is inactive.'], 403);
        }

        $device = null;
        if (! empty($data['device_uid'])) {
            $device = PosDevice::updateOrCreate(
                ['device_uid' => $data['device_uid']],
                [
                    'device_name' => $data['device_name'] ?? null,
                    'showroom_id' => $data['showroom_id'] ?? null,
                    'registered_by_admin_id' => $admin->id,
                    'last_seen_at' => now(),
                    'status' => 'active',
                ]
            );
        }

        $token = Str::random(80);
        $abilities = $this->permissionService->abilitiesFor($admin);
        ShowroomSession::create([
            'admin_id' => $admin->id,
            'pos_device_id' => $device?->id,
            'token_hash' => hash('sha256', $token),
            'abilities' => $abilities,
            'expires_at' => now()->addDays(30),
            'ip_address' => $request->ip(),
            'user_agent' => $request->userAgent(),
        ]);

        return response()->json([
            'token_type' => 'Bearer',
            'access_token' => $token,
            'expires_in_days' => 30,
            'admin' => [
                'id' => $admin->id,
                'name' => trim($admin->f_name . ' ' . $admin->l_name),
                'email' => $admin->email,
                'role_id' => $admin->role_id,
            ],
            'abilities' => $abilities,
            'device' => $device,
        ]);
    }

    public function logout(Request $request)
    {
        $session = $request->attributes->get('showroom_session');
        if ($session) {
            $session->update(['revoked_at' => now()]);
        }

        return response()->json(['message' => 'Logged out.']);
    }
}
