<?php

declare(strict_types=1);

namespace App\Filament\Resources\SpaNews;

use App\Filament\Resources\SpaNews\Pages\CreateSpaNews;
use App\Filament\Resources\SpaNews\Pages\EditSpaNews;
use App\Filament\Resources\SpaNews\Pages\ListSpaNews;
use App\Models\Post;
use App\Models\User;
use App\Support\Filament\ContentCrud\ContentFields;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use UnitEnum;

class SpaNewsResource extends Resource
{
    protected static ?string $model = Post::class;

    protected static ?string $recordTitleAttribute = 'title';

    protected static ?string $slug = 'spa-news';

    protected static ?string $navigationLabel = '最新消息';

    protected static string|UnitEnum|null $navigationGroup = '怡SPA';

    protected static ?int $navigationSort = 10;

    protected static ?string $modelLabel = '最新消息';

    protected static ?string $pluralModelLabel = '最新消息';

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-newspaper';

    public static function canViewAny(): bool
    {
        $user = Auth::user();

        return $user instanceof User
            && $user->hasAnyRole(['super_admin', 'admin']);
    }

    public static function canCreate(): bool
    {
        return static::canViewAny();
    }

    public static function canEdit(Model $record): bool
    {
        return static::canViewAny();
    }

    public static function canDelete(Model $record): bool
    {
        return static::canViewAny();
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->where('section', 'spa_news');
    }

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components(ContentFields::defaultFormComponents(
                section: 'spa_news',
                uploadDirectory: 'posts/spa-news',
            ));
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns(ContentFields::defaultTableColumns())
            ->reorderable('sort_order')
            ->actions([
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->bulkActions([
                DeleteBulkAction::make(),
            ])
            ->defaultSort('sort_order', 'asc');
    }

    public static function getPages(): array
    {
        return [
            'index' => ListSpaNews::route('/'),
            'create' => CreateSpaNews::route('/create'),
            'edit' => EditSpaNews::route('/{record}/edit'),
        ];
    }
}
