<?php

namespace App\Filament\Exports;

use App\Models\User;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;

class UserExporter extends Exporter
{
    protected static ?string $model = User::class;

    public static function getColumns(): array
    {
        return [
            ExportColumn::make('id')
                ->label(__('common.id')),
            ExportColumn::make('name')
                ->label(__('common.name')),
            ExportColumn::make('job_title')
                ->label(__('common.job_title')),
            ExportColumn::make('email')
                ->label(__('common.email')),
            ExportColumn::make('phone_number')
                ->label(__('common.phone_number')),
            ExportColumn::make('association.name')
                ->label(__('common.association')),
            ExportColumn::make('roles')
                ->label(__('common.roles'))
                ->state(function (User $record): ?string {
                    $roles = $record->roles;

                    return $roles->isNotEmpty() ? $roles->pluck('name')->join(', ') : null;
                }),
            ExportColumn::make('departments')
                ->label(__('common.departments'))
                ->state(function (User $record): ?string {
                    $departments = $record->departments;

                    return $departments->isNotEmpty() ? $departments->pluck('name')->join(', ') : null;
                }),
            ExportColumn::make('email_verified_at')
                ->label(__('common.email_verified_at')),
            ExportColumn::make('created_at')
                ->label(__('common.created_at')),
            ExportColumn::make('updated_at')
                ->label(__('common.updated_at')),
        ];
    }

    public static function getCompletedNotificationBody(Export $export): string
    {
        $successfulRows = $export->successful_rows;
        $rowWord = $successfulRows === 1 ? __('common.row') : __('common.rows');

        $body = __('common.export_completed', [
            'count' => number_format($successfulRows),
            'rows' => $rowWord,
        ]);

        if ($failedRowsCount = $export->getFailedRowsCount()) {
            $failedRowWord = $failedRowsCount === 1 ? __('common.row') : __('common.rows');
            $body .= __('common.export_failed_rows', [
                'count' => number_format($failedRowsCount),
                'rows' => $failedRowWord,
            ]);
        }

        return $body;
    }
}
