<?php

namespace App\Services;

use App\Data\LoginRequest;
use App\Data\LoginResponse;
use App\Data\UserData;
use App\Helpers\UrlHelper;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class AuthService
{
    /**
     * Authenticate user and return login response
     */
    public function login(LoginRequest $loginRequest): LoginResponse
    {
        $credentials = [
            'email' => $loginRequest->email,
            'password' => $loginRequest->password,
        ];

        // Check if user exists first
        $user = User::where('email', $loginRequest->email)->first();
        
        // If user doesn't exist, just throw invalid credentials without revealing
        if (!$user) {
            throw ValidationException::withMessages([
                'email' => ['Invalid credentials.'],
            ]);
        }

        // Check if user is active before attempting login
        if ($user->status !== 1) { // 1=ACTIVE
            $statusMessage = match($user->status) {
                2 => 'Your account is pending approval. Please wait for admin approval.', // 2=INACTIVE
                3 => 'Your account has been suspended. Please contact administrator.', // 3=SUSPENDED
                default => 'Your account is not active. Please contact administrator.',
            };
            
            throw ValidationException::withMessages([
                'email' => [$statusMessage],
            ]);
        }

        // Attempt authentication
        if (!Auth::attempt($credentials)) {
            throw ValidationException::withMessages([
                'email' => ['Invalid credentials.'],
            ]);
        }

        $user = Auth::user();

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

        // Get user permissions and roles
        $permissions = $user->getAllPermissions()->pluck('name')->toArray();
        $roles = $user->getRoleNames()->toArray();

        // Create user data for response
        $userData = new UserData(
            name: $user->name,
            email: $user->email,
            password: '', // Don't include password in response
            phone: $user->phone,
            role_type: $user->role_type,
            profile_photo: UrlHelper::toFullUrl($user->profile_photo),
            status: $user->status,
        );

        return LoginResponse::success($token, $userData, $permissions, $roles);
    }

    /**
     * Logout user (revoke all tokens)
     */
    public function logout(User $user): bool
    {
        return $user->tokens()->delete() > 0;
    }

    /**
     * Logout from specific device
     */
    public function logoutFromDevice(User $user, string $tokenId): bool
    {
        return $user->tokens()->where('id', $tokenId)->delete() > 0;
    }

    /**
     * Get current authenticated user
     */
    public function getCurrentUser(): ?User
    {
        return Auth::user();
    }

    /**
     * Check if user is authenticated
     */
    public function isAuthenticated(): bool
    {
        return Auth::check();
    }

    /**
     * Get user permissions
     */
    public function getUserPermissions(User $user): array
    {
        return $user->getAllPermissions()->pluck('name')->toArray();
    }

    /**
     * Get user roles
     */
    public function getUserRoles(User $user): array
    {
        return $user->getRoleNames()->toArray();
    }

    /**
     * Format user profile data for API response
     */
    public function formatUserProfile(User $user): array
    {
        $permissions = $this->getUserPermissions($user);
        $roles = $this->getUserRoles($user);

        return [
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone,
                'role_type' => $user->role_type,
                'profile_photo' => UrlHelper::toFullUrl($user->profile_photo),
                'status' => $user->status,
                'email_verified_at' => $user->email_verified_at,
                'created_at' => $user->created_at,
                'updated_at' => $user->updated_at,
            ],
            'permissions' => $permissions,
            'roles' => $roles,
        ];
    }
}
