<?php

namespace App\Http\Services;

use App\Models\User;
use Illuminate\Support\Facades\Hash;

class LoginService
{
    public function attemptLogin($account, $password)
    {
        $user = User::where('account', $account)->first();

        if (!$user) {
            // If no user is found with the provided credentials
            return response([
                'message' => ['No account found with the provided credentials.']
            ], 404); // Using 404 to indicate "Not Found"
        } elseif (!Hash::check($password, $user->password)) {
            // If the user is found but the password does not match
            return response([
                'message' => ['The provided password is incorrect.']
            ], 401); // Keeping 401 for "Unauthorized"
        }

        $roles = [$user->role];

        // Customize the switch case based on your specific roles and abilities
        $abilities = $this->getAbilitiesBasedOnRole($roles);

        $token = $user->createToken('pdet-token', [])->plainTextToken;
        \Log::info('Generated token: ' . $token);
        $response = [
            'userData' => $user,
            'accessToken' => $token,
            'userAbilityRules' => $abilities,
        ];

        return response($response, 201);
    }

    private function getAbilitiesBasedOnRole($roles)
    {
        $abilities[] = ['action' => 'read', 'subject' => 'base'];

        if (in_array('admin', $roles)) {
            $abilities[] = ['action' => 'read', 'subject' => 'all'];
        }

        if (in_array('project_manager', $roles)) {
            $abilities[] = ['action' => 'manage', 'subject' => 'projects'];
        }

        if (in_array('editor', $roles)) {
            $abilities[] = ['action' => 'read', 'subject' => 'projects'];
            $abilities[] = ['action' => 'create', 'subject' => 'projects'];
            $abilities[] = ['action' => 'update', 'subject' => 'projects'];
            $abilities[] = ['action' => 'delete', 'subject' => 'projects'];
        }

        if (in_array('maintainer', $roles)) {
            $abilities[] = ['action' => 'manage', 'subject' => 'all'];
        }

        if (empty($abilities)) { // Default fallback if no roles match
            $abilities[] = ['action' => 'read', 'subject' => 'public_data'];
        }

        return $abilities;
    }
}
