<?php

namespace App\Filament\Resources\Manage\Journalists;

use App\Enums\RoleEnum;
use App\Filament\Resources\Manage\Journalists\Pages\ManageJournalists;
use App\Filament\Resources\Manage\Journalists\Schemas\JournalistForm;
use App\Filament\Resources\Manage\Journalists\Tables\JournalistTable;
use App\Models\Journalist;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;

class JournalistResource extends Resource
{
    protected static ?string $model = Journalist::class;

    protected static string|UnitEnum|null $navigationGroup = 'Kelola';

    protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedIdentification;

    protected static ?string $navigationLabel = 'Jurnalis';

    protected static ?int $navigationSort = 4;

    protected static ?string $slug = 'manage/journalists';

    public static function form(Schema $schema): Schema
    {
        return JournalistForm::configure($schema);
    }

    public static function table(Table $table): Table
    {
        return JournalistTable::configure($table);
    }

    public static function getPages(): array
    {
        return [
            'index' => ManageJournalists::route('/'),
        ];
    }

    public static function getEloquentQuery(): Builder
    {
        return parent::getEloquentQuery()
            ->when(fn () => auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value) && ! auth()->user()->company?->partnerMedia, function (Builder $query): Builder {
                return $query->whereRaw('1 = 0');
            })
            ->when(auth()->user()->hasRole(RoleEnum::PERUSAHAAN->value), function (Builder $query): Builder {
                return $query->whereHas('partnerMedia.company', function (Builder $q): void {
                    $q->where('user_id', auth()->id());
                });
            });
    }
}
