<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'username' => $this->username,
            'name' => $this->name,
            'email' => $this->email,
            'phone' => $this->phone,
            'avatar' => $this->avatar,
            'status' => $this->status,
            'last_login_at' => $this->formatDate($this->last_login_at),
            'last_login_ip' => $this->last_login_ip,
            'login_count' => $this->login_count,
            'password_changed_at' => $this->formatDate($this->password_changed_at),
            'create_time' => $this->formatDate($this->create_time),
            'update_time' => $this->formatDate($this->update_time),
            'roles' => $this->whenLoaded('roles', function () {
                return $this->roles->map(function ($role) {
                    return [
                        'id' => $role->id,
                        'name' => $role->name,
                        'code' => $role->code,
                    ];
                });
            }),
            // 扩展字段：show 时由 UserService 附加；其他场景不存在时不输出
            'ext_fields' => $this->when(isset($this->resource->ext_fields), function () {
                return $this->resource->ext_fields;
            }),
            // 当前登录用户是否可以管理该账号（编辑/删除/重置密码等）
            // 超管可管理所有账号；非超管只能管理可管辖角色范围内的账号
            'can_manage' => $this->when($this->shouldIncludeCanManage(), function () {
                return $this->resolveCanManage();
            }),
        ];
    }

    /**
     * 统一日期格式为 Y-m-d H:i:s（项目规范：禁止 ISO 8601）
     */
    private function formatDate($date): ?string
    {
        if (!$date) {
            return null;
        }
        if ($date instanceof \DateTimeInterface) {
            return $date->format('Y-m-d H:i:s');
        }
        return (string) $date;
    }

    /**
     * 判断是否需要计算 can_manage 字段
     *
     * 仅在 admin 域认证上下文下计算（避免前台等场景误算）
     */
    private function shouldIncludeCanManage(): bool
    {
        return auth('admin')->check();
    }

    /**
     * 解析当前登录用户是否可以管理该账号
     *
     * 规则（与 UserService::canManageUser 对齐）：
     *   - 超权账号（id=1 或 super_admin 角色）可管理所有账号
     *   - 非超权账号只能管理拥有可管辖角色（自身角色分支内）的账号
     */
    private function resolveCanManage(): bool
    {
        $currentUser = auth('admin')->user();
        if (! $currentUser) {
            return false;
        }

        // 超权账号可管理所有账号
        if ($currentUser->id === 1 || $currentUser->isSuperAdmin()) {
            return true;
        }

        // 非超权：目标用户必须拥有至少一个在可管辖范围内的角色
        $manageableRoleIds = app(\App\Services\UserService::class)
            ->getManageableRoleIds($currentUser);

        if (empty($manageableRoleIds)) {
            return false;
        }

        return $this->resource->roles()
            ->whereIn('admin_roles.id', $manageableRoleIds)
            ->exists();
    }
}
