<?php

namespace Maestro\Core\DataTables\Resources;

use Maestro\Core\DataTables\DataTableResource;
use App\Services\Access\PermissionResolver;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;

/**
 * DataTable resource for roles (Spatie). Table: roles.
 * created_at/updated_at included only if the roles table has them.
 */
class RolesTable implements DataTableResource
{
    public function key(): string
    {
        return 'roles';
    }

    /**
     * Require authenticated user with module access to roles (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(), 'roles.view')) {
            throw new AuthorizationException('You do not have permission to view roles.');
        }
    }

    /**
     * Base query. Select safe columns; eager load permission names.
     */
    public function baseQuery(Request $request): Builder
    {
        $pivotTable = config('permission.table_names.model_has_roles', 'model_has_roles');
        $query = Role::query()
            ->select(['roles.id', 'roles.name', 'roles.guard_name'])
            ->withCount('permissions')
            ->with(['permissions:id,name'])
            ->selectSub(
                DB::table($pivotTable)->selectRaw('count(0)')->whereColumn($pivotTable . '.role_id', 'roles.id'),
                'users_count'
            );

        if (Schema::hasColumn('roles', 'created_at')) {
            $query->addSelect('roles.created_at');
        }
        if (Schema::hasColumn('roles', 'updated_at')) {
            $query->addSelect('roles.updated_at');
        }

        return $query;
    }

    public function columns(): array
    {
        $cols = [
            [
                'key' => 'id',
                'expr' => 'roles.id',
                'type' => 'number',
                'sortable' => true,
                'searchable' => false,
                'filterable' => false,
                'filterMode' => 'equals',
                'label' => __('datatable.columns.roles.id'),
                'defaultVisible' => false,
            ],
            [
                'key' => 'name',
                'expr' => 'roles.name',
                'type' => 'text',
                'sortable' => true,
                'searchable' => true,
                'filterable' => true,
                'filterMode' => 'contains',
                'label' => __('datatable.columns.roles.name'),
                'defaultVisible' => true,
            ],
            [
                'key' => 'guard_name',
                'expr' => 'roles.guard_name',
                'type' => 'text',
                'sortable' => true,
                'searchable' => true,
                'filterable' => true,
                'filterMode' => 'contains',
                'label' => __('datatable.columns.roles.guard_name'),
                'defaultVisible' => false,
            ],
            [
                'key' => 'permissions',
                'expr' => 'roles.id',
                'type' => 'text',
                'sortable' => false,
                'searchable' => false,
                'filterable' => false,
                'filterMode' => 'contains',
                'label' => __('datatable.columns.roles.permissions'),
                'defaultVisible' => false,
            ],
        ];

        $cols[] = [
            'key' => 'permissions_count',
            'expr' => 'permissions_count',
            'type' => 'number',
            'sortable' => true,
            'searchable' => false,
            'filterable' => true,
            'filterMode' => 'equals',
            'label' => __('datatable.columns.roles.permissions_count'),
            'defaultVisible' => true,
        ];
        $cols[] = [
            'key' => 'users_count',
            'expr' => 'users_count',
            'type' => 'number',
            'sortable' => true,
            'searchable' => false,
            'filterable' => true,
            'filterMode' => 'equals',
            'label' => __('datatable.columns.roles.users_count'),
            'defaultVisible' => true,
        ];
        if (Schema::hasColumn('roles', 'created_at')) {
            $cols[] = [
                'key' => 'created_at',
                'expr' => 'roles.created_at',
                'type' => 'date',
                'sortable' => true,
                'searchable' => false,
                'filterable' => true,
                'filterMode' => 'date_equals',
                'label' => __('datatable.columns.roles.created_at'),
                'defaultVisible' => false,
            ];
        }
        if (Schema::hasColumn('roles', 'updated_at')) {
            $cols[] = [
                'key' => 'updated_at',
                'expr' => 'roles.updated_at',
                'type' => 'date',
                'sortable' => true,
                'searchable' => false,
                'filterable' => true,
                'filterMode' => 'date_equals',
                'label' => __('datatable.columns.roles.updated_at'),
                'defaultVisible' => true,
            ];
        }

        return $cols;
    }

    /**
     * @param  object  $model  Role instance (with permissions loaded)
     * @return array<string, mixed>
     */
    public function transformRow(object $model): array
    {
        $createdAt = isset($model->created_at) ? $model->created_at : null;
        $updatedAt = isset($model->updated_at) ? $model->updated_at : null;

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

        $row = [
            'id' => $model->id,
            'name' => $model->name ?? '',
            'guard_name' => $model->guard_name ?? '',
            'permissions' => implode(', ', $permissions),
            'permissions_count' => (int) ($model->permissions_count ?? count($permissions)),
            'users_count' => (int) ($model->users_count ?? 0),
        ];

        if (Schema::hasColumn('roles', 'created_at') && $createdAt !== null) {
            $row['created_at'] = $createdAt instanceof \DateTimeInterface
                ? $createdAt->format('Y-m-d H:i:s')
                : (string) $createdAt;
        }
        if (Schema::hasColumn('roles', 'updated_at') && $updatedAt !== null) {
            $row['updated_at'] = $updatedAt instanceof \DateTimeInterface
                ? $updatedAt->format('Y-m-d H:i:s')
                : (string) $updatedAt;
        }

        return $row;
    }
}
