<?php

namespace App\Repositories\Eloquent;

use App\Enum\Status;
use App\Models\Buyer\Buyer;
use App\Models\Role;
use App\Models\User;
use App\Repositories\Contracts\UserRepositoryInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class UserRepository extends BaseRepository implements UserRepositoryInterface
{

    /**
     * Create a user with buyer role.
     *
     * @param array $userData
     * @param array $settings
     * @return User
     */
    public function createBuyer(array $userData, array $settings = []): User
    {
        // Create buyer model first
        $buyer = Buyer::create([]);

        // Hash password if provided
        if (isset($userData['password'])) {
            $userData['password'] = Hash::make($userData['password']);
        }

        // Set default status if not provided
        if (!isset($userData['status'])) {
            $userData['status'] = Status::ACTIVE;
        }

        // Create user associated with buyer
        $user = $buyer->user()->create($userData);

        // Create default settings if not provided
        $defaultSettings = [
            ['key' => 'is_dark_mode', 'value' => false],
            ['key' => 'is_compact_sidebar', 'value' => false],
        ];

        $settingsToCreate = !empty($settings) ? $settings : $defaultSettings;
        $user->settings()->createMany($settingsToCreate);

        // Assign buyer role
        $user->assignRole(Role::BUYER);

        return $user->fresh(['model']);
    }

    /**
     * Find user by email.
     *
     * @param string $email
     * @return User|null
     */
    public function findByEmail(string $email): ?User
    {
        return $this->model->where('email', $email)->first();
    }

    /**
     * Authenticate user (login).
     *
     * @param array $credentials
     * @param bool $remember
     * @return bool
     */
    public function authenticate(array $credentials, bool $remember = false): bool
    {
        return Auth::attempt($credentials, $remember);
    }

    /**
     * Get authenticated user.
     *
     * @return User|null
     */
    public function getAuthenticatedUser(): ?User
    {
        return Auth::user();
    }

    /**
     * Logout authenticated user.
     *
     * @return void
     */
    public function logout(): void
    {
        Auth::logout();
    }
}

