<?php

namespace App\Domains\Auth\Services;

use App\Domains\Auth\Models\Admin;
use App\Domains\Auth\Repositories\Contracts\AdminRepositoryInterface;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthService
{
    public function __construct(
        private AdminRepositoryInterface $adminRepository
    ) {}

    /**
     * Authenticate admin and return token with admin data.
     *
     * @param Request $request
     * @return array{token: string, token_type: string, admin: Admin}
     */
    public function login(Request $request): array
    {
        $admin = $this->adminRepository->findByEmail($request->email);

        if (!$admin || !Hash::check($request->password, $admin->password)) {
            throw new AuthenticationException('Invalid credentials');
        }

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

        return [
            'token' => $token,
            'token_type' => 'Bearer',
            'admin' => $admin,
        ];
    }

    /**
     * Delete the current access token for the authenticated admin.
     *
     * @param Admin $admin
     * @return void
     */
    public function logout(Admin $admin): void
    {
        /** @var \Laravel\Sanctum\PersonalAccessToken|null $token */
        $token = $admin->currentAccessToken();
        $token?->delete();
    }

    /**
     * Return the authenticated admin.
     *
     * @param Admin $admin
     * @return Admin
     */
    public function me(Admin $admin): Admin
    {
        return $admin;
    }
}