<?php

namespace Maestro\Core\DataTables\Resources;

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

/**
 * DataTable resource for subsidy grantors. Table: subsidy_grantors.
 * Safe columns: id, name, description, created_at, updated_at (+ computed postcode_ranges).
 */
class SubsidyGrantorsTable implements DataTableResource
{
    private const RANGES_TABLE = 'subsidy_grantor_postcode_ranges';

    public function key(): string
    {
        return 'subsidy-grantors';
    }

    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(), 'subsidygrantors.view')) {
            throw new AuthorizationException('You do not have permission to view subsidy grantors.');
        }
    }

    public function baseQuery(Request $request): Builder
    {
        return SubsidyGrantor::query()->select(['id', 'name', 'description', 'created_at', 'updated_at']);
    }

    public function columns(): array
    {
        return [
            [
                'key' => 'id',
                'expr' => 'subsidy_grantors.id',
                'type' => 'number',
                'sortable' => true,
                'searchable' => false,
                'filterable' => false,
                'filterMode' => 'equals',
                'label' => __('datatable.columns.subsidy-grantors.id'),
                'defaultVisible' => false,
            ],
            [
                'key' => 'name',
                'expr' => 'subsidy_grantors.name',
                'type' => 'text',
                'sortable' => true,
                'searchable' => true,
                'filterable' => true,
                'filterMode' => 'contains',
                'label' => __('datatable.columns.subsidy-grantors.name'),
                'defaultVisible' => true,
            ],
            [
                'key' => 'description',
                'expr' => 'subsidy_grantors.description',
                'type' => 'text',
                'sortable' => true,
                'searchable' => true,
                'filterable' => true,
                'filterMode' => 'contains',
                'label' => __('datatable.columns.subsidy-grantors.description'),
                'defaultVisible' => true,
            ],
            [
                'key' => 'postcode_ranges',
                'expr' => 'subsidy_grantors.id',
                'type' => 'text',
                'sortable' => false,
                'searchable' => false,
                'filterable' => false,
                'filterMode' => 'contains',
                'label' => __('datatable.columns.subsidy-grantors.postcode_ranges'),
                'defaultVisible' => true,
            ],
            [
                'key' => 'created_at',
                'expr' => 'subsidy_grantors.created_at',
                'type' => 'date',
                'sortable' => true,
                'searchable' => false,
                'filterable' => true,
                'filterMode' => 'date_equals',
                'label' => __('datatable.columns.subsidy-grantors.created_at'),
                'defaultVisible' => false,
            ],
            [
                'key' => 'updated_at',
                'expr' => 'subsidy_grantors.updated_at',
                'type' => 'date',
                'sortable' => true,
                'searchable' => false,
                'filterable' => true,
                'filterMode' => 'date_equals',
                'label' => __('datatable.columns.subsidy-grantors.updated_at'),
                'defaultVisible' => false,
            ],
        ];
    }

    public function transformRow(object $model): array
    {
        $formatDate = fn ($v) => $v instanceof \DateTimeInterface ? $v->format('Y-m-d H:i:s') : (string) $v;

        $ranges = DB::table(self::RANGES_TABLE)
            ->where('subsidy_grantor_id', $model->id)
            ->orderBy('postcode_from')
            ->get();

        $rangeLabel = $ranges->count()
            ? $ranges->map(fn ($r) => ((int) $r->postcode_from) . '-' . ((int) $r->postcode_to))->implode(', ')
            : '';

        return [
            'id' => $model->id,
            'name' => $model->name ?? '',
            'description' => $model->description ?? '',
            'postcode_ranges' => $rangeLabel,
            'created_at' => $formatDate($model->created_at ?? null),
            'updated_at' => $formatDate($model->updated_at ?? null),
        ];
    }
}

