<?php

namespace App\Services;

use App\Http\Responses\ApiResponse;
use App\Models\AdminUser;
use Illuminate\Support\Facades\Hash;

class AuthService
{
    public function login(string $username, string $password): array
    {
        $user = AdminUser::where('username', $username)->first();

        if (! $user || ! Hash::check($password, $user->password)) {
            return ApiResponse::error(40001, '用户名或密码错误');
        }

        if ($user->status->value !== 1) {
            return ApiResponse::error(40102, '账号已被禁用');
        }

        $user->update([
            'last_login_at' => now(),
            'last_login_ip' => request()->ip(),
            'login_count' => $user->login_count + 1,
        ]);

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

        return ApiResponse::success(['token' => $token]);
    }

    public function logout(AdminUser $user): array
    {
        // 兼容 Session 和 Token 两种认证模式
        $token = $user->currentAccessToken();
        if ($token) {
            $token->delete();
        }
        // Session 模式下通过中间件处理登出

        return ApiResponse::success(null, '退出成功');
    }

    public function getUser(AdminUser $user): array
    {
        $user->load('roles');

        return ApiResponse::success([
            'id' => $user->id,
            'username' => $user->username,
            'name' => $user->name,
            'email' => $user->email,
            'phone' => $user->phone,
            'avatar' => $user->avatar,
            'status' => $user->status->value,
            'last_login_at' => $user->last_login_at?->toDateTimeString(),
            'permissions' => $user->isSuperAdmin() ? ['*'] : $user->getAllPermissions(),
        ]);
    }

    public function changePassword(AdminUser $user, string $oldPassword, string $newPassword): array
    {
        if (! Hash::check($oldPassword, $user->password)) {
            return ApiResponse::error(40001, '原密码错误');
        }

        $user->update([
            'password' => Hash::make($newPassword),
            'password_changed_at' => now(),
        ]);

        return ApiResponse::success(null, '密码修改成功');
    }

    public function refresh(AdminUser $user): array
    {
        $token = $user->currentAccessToken();
        if ($token) {
            $token->delete();
        }
        $token = $user->createToken('admin-token')->plainTextToken;

        return ApiResponse::success(['token' => $token]);
    }
}
