<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

namespace App\Filament\Resources\DberpDbshopInventorySyncs;

use App\Business\Integration\DbshopIntegrationService;
use App\Filament\Concerns\HidesDberpIntegrationCenterNavigation;
use App\Filament\Concerns\InteractsWithDberpPermissions;
use App\Filament\Resources\DberpDbshopInventorySyncs\Pages\ListDberpDbshopInventorySyncs;
use App\Models\DberpProduct;
use App\Services\DberpPermissionService;
use App\Support\DberpNumberFormatter;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use UnitEnum;

class DberpDbshopInventorySyncResource extends Resource
{
    use HidesDberpIntegrationCenterNavigation;
    use InteractsWithDberpPermissions;

    protected static ?string $model = DberpProduct::class;

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?int $navigationSort = 40;

    public static function form(Schema $schema): Schema
    {
        return $schema->components([]);
    }

    public static function getEloquentQuery(): Builder
    {
        return DberpProduct::query()
            ->with('inventoryBalances')
            ->whereHas('integrationMappings', function (Builder $query): void {
                $query->where('source_system', 'dbshop')->where('object_type', 'product');
            });
    }

    public static function table(Table $table): Table
    {
        return $table
            ->defaultSort('last_integration_synced_at', 'desc')
            ->columns([
                TextColumn::make('code')->label(__('dberp.fields.product_code'))->searchable(),
                TextColumn::make('name')->label(__('dberp.fields.product_name'))->searchable(),
                TextColumn::make('external_product_id')->label(__('dberp.fields.external_product_id'))->searchable(),
                TextColumn::make('external_sku')->label(__('dberp.fields.external_sku'))->searchable(),
                TextColumn::make('realtime_quantity_total')
                    ->label(__('dberp.fields.realtime_quantity'))
                    ->state(fn (DberpProduct $record): string => DberpNumberFormatter::quantity($record->inventoryBalances->sum('realtime_quantity'))),
                TextColumn::make('available_quantity_total')
                    ->label(__('dberp.fields.available_quantity'))
                    ->state(fn (DberpProduct $record): string => DberpNumberFormatter::quantity($record->inventoryBalances->sum('available_quantity'))),
                TextColumn::make('last_integration_synced_at')->label(__('dberp.fields.last_integration_synced_at'))->dateTime(),
            ])
            ->headerActions([
                Action::make('sync_dbshop_inventory')
                    ->label(__('dberp.actions.sync_dbshop_inventory'))
                    ->requiresConfirmation()
                    ->visible(fn (): bool => app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE))
                    ->action(function (): void {
                        $count = app(DbshopIntegrationService::class)->syncInventoryBatch();

                        Notification::make()
                            ->title(__('dberp.actions.sync_dbshop_inventory')."：{$count}")
                            ->success()
                            ->send();
                    }),
            ])
            ->recordActions([
                Action::make('sync_inventory_single')
                    ->label(__('dberp.actions.retry_sync'))
                    ->visible(fn (): bool => app(DberpPermissionService::class)->allows(Auth::user(), DberpPermissionService::MANAGE_INTEGRATION_MAPPING_GOVERNANCE))
                    ->action(function (DberpProduct $record): void {
                        app(DbshopIntegrationService::class)->syncInventoryForProduct($record);

                        Notification::make()->title(__('dberp.notifications.completed'))->success()->send();
                    }),
            ]);
    }

    public static function canViewAny(): bool
    {
        return static::canAccessIntegrationCenter()
            && static::allowsPermission(DberpPermissionService::VIEW_INTEGRATION_DBSHOP_SYNC);
    }

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

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

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

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

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

    public static function getNavigationGroup(): string|UnitEnum|null
    {
        return __('dberp.nav.integration');
    }

    public static function getNavigationIcon(): string|BackedEnum|Htmlable|null
    {
        return null;
    }

    public static function getModelLabel(): string
    {
        return __('dberp.resources.dbshop_inventory_sync.label');
    }

    public static function getPluralModelLabel(): string
    {
        return __('dberp.resources.dbshop_inventory_sync.plural');
    }
}
