<?php

namespace App\Filament\Widgets;

use App\Models\Website;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;
use Illuminate\Database\Eloquent\Builder;

class WebsiteRequestsWidget extends TableWidget
{
    protected static ?string $heading = 'Websites by Current Month Requests';

    protected static ?int $sort = 1;

    protected int | string | array $columnSpan = 1;

    public function table(Table $table): Table
    {
        return $table
            ->query(fn (): Builder => Website::query()
                ->withCount(['apiRequests' => fn (Builder $query) => $query
                    ->whereBetween('created_at', [now()->startOfMonth(), now()->endOfMonth()])
                ])
                ->orderByDesc('api_requests_count')
            )
            ->columns([
                TextColumn::make('name'),
                TextColumn::make('tier.name')
                    ->label('Tier'),
                TextColumn::make('api_requests_count')
                    ->label('Requests This Month')
                    ->numeric()
                    ->alignEnd(),
            ])
            ->searchable(false)
            ->paginated(false);
    }
}
