<?php

namespace Maestro\Core\DataTables\Resources;

use Maestro\Core\DataTables\DataTableResource;
use Maestro\Core\Models\User;
use App\Services\Access\PermissionResolver;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

/**
 * DataTable resource for users. Table: users.
 * Only safe columns exposed; no password, remember_token, or tokens.
 */
class UsersTable implements DataTableResource
{
    public function key(): string
    {
        return 'users';
    }

    /**
     * Require authenticated user with module access to users (resolver global or Spatie).
     */
    public function authorize(Request $request): void
    {
        if (! $request->user()) {
            throw new AuthorizationException('You are not authorized to access this DataTable resource.');
        }
        $resolver = app(PermissionResolver::class);
        if (! $resolver->userHasModuleAccess($request->user(), 'users.view')) {
            throw new AuthorizationException('You do not have permission to view users.');
        }
    }

    /**
     * Base query. Select only safe columns; eager load role names.
     */
    public function baseQuery(Request $request): Builder
    {
        return User::query()
            ->select(['id', 'name', 'email', 'is_active', 'identity_source', 'microsoft_user_id', 'last_login_at', 'created_at'])
            ->with(['roles:id,name']);
    }

    public function columns(): array
    {
        return [
            [
                'key' => 'id',
                'expr' => 'users.id',
                'type' => 'number',
                'sortable' => true,
                'searchable' => false,
                'filterable' => false,
                'filterMode' => 'equals',
                'label' => __('datatable.columns.users.id'),
                'defaultVisible' => false,
            ],
            [
                'key' => 'name',
                'expr' => 'users.name',
                'type' => 'text',
                'sortable' => true,
                'searchable' => true,
                'filterable' => true,
                'filterMode' => 'contains',
                'label' => __('datatable.columns.users.name'),
                'defaultVisible' => true,
            ],
            [
                'key' => 'email',
                'expr' => 'users.email',
                'type' => 'text',
                'sortable' => true,
                'searchable' => true,
                'filterable' => true,
                'filterMode' => 'contains',
                'label' => __('datatable.columns.users.email'),
                'defaultVisible' => true,
            ],
            [
                'key' => 'identity_source',
                'expr' => 'users.identity_source',
                'type' => 'badge',
                'sortable' => true,
                'searchable' => false,
                'filterable' => true,
                'filterMode' => 'equals',
                'label' => __('datatable.columns.users.identity_source'),
                'defaultVisible' => true,
            ],
            [
                'key' => 'guest_linked',
                'expr' => 'users.identity_source',
                'type' => 'badge',
                'sortable' => true,
                'searchable' => false,
                'filterable' => true,
                'filterMode' => 'equals',
                'label' => __('datatable.columns.users.user_type'),
                'defaultVisible' => true,
            ],
            [
                'key' => 'roles',
                'expr' => 'users.id',
                'type' => 'text',
                'sortable' => false,
                'searchable' => false,
                'filterable' => false,
                'filterMode' => 'contains',
                'label' => __('datatable.columns.users.roles'),
                'defaultVisible' => true,
            ],
            [
                'key' => 'is_active',
                'expr' => 'users.is_active',
                'type' => 'boolean',
                'sortable' => true,
                'searchable' => false,
                'filterable' => true,
                'filterMode' => 'equals',
                'label' => __('datatable.columns.users.is_active'),
                'defaultVisible' => true,
            ],
            [
                'key' => 'last_login_at',
                'expr' => 'users.last_login_at',
                'type' => 'date',
                'sortable' => true,
                'searchable' => false,
                'filterable' => true,
                'filterMode' => 'date_equals',
                'label' => __('datatable.columns.users.last_login_at'),
                'defaultVisible' => false,
            ],
            [
                'key' => 'created_at',
                'expr' => 'users.created_at',
                'type' => 'date',
                'sortable' => true,
                'searchable' => false,
                'filterable' => true,
                'filterMode' => 'date_equals',
                'label' => __('datatable.columns.users.created_at'),
                'defaultVisible' => true,
            ],
        ];
    }

    /**
     * @param  object  $model  User instance (with roles loaded)
     * @return array<string, mixed>
     */
    public function transformRow(object $model): array
    {
        $lastLoginAt = $model->last_login_at ?? null;
        $createdAt = $model->created_at ?? null;

        $roleNames = $model->roles ?? collect();
        $roles = is_iterable($roleNames) ? collect($roleNames)->pluck('name')->filter()->values()->all() : [];

        $identitySource = $model->identity_source ?? 'local';
        $guestLinked = $identitySource === 'microsoft'
            ? 'microsoft'
            : (! empty($model->microsoft_user_id) ? 'guest_linked' : 'guest_pending');

        return [
            'id' => $model->id,
            'name' => $model->name ?? '',
            'email' => $model->email ?? '',
            'identity_source' => $identitySource,
            'microsoft_user_id' => $model->microsoft_user_id,
            'guest_linked' => $guestLinked,
            'is_active' => (bool) ($model->is_active ?? false),
            'last_login_at' => $lastLoginAt instanceof \DateTimeInterface ? $lastLoginAt->format('Y-m-d H:i:s') : (string) $lastLoginAt,
            'created_at' => $createdAt instanceof \DateTimeInterface ? $createdAt->format('Y-m-d H:i:s') : (string) $createdAt,
            'roles' => implode(', ', $roles),
        ];
    }
}
