<?php

namespace App\Filament\Clusters\DailyOps\Resources\TenantPaddleHealths;

use App\Filament\Clusters\DailyOps\DailyOpsCluster;
use App\Filament\Clusters\DailyOps\Resources\TenantPaddleHealths\Pages\ListTenantPaddleHealths;
use App\Filament\Clusters\DailyOps\Resources\TenantPaddleHealths\Tables\TenantPaddleHealthTable;
use App\Models\CheckoutSession;
use App\Models\Tenant;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;

class TenantPaddleHealthResource extends Resource
{
    public const STALE_SYNC_DAYS = 30;

    public const TRANSACTION_WINDOW_DAYS = 30;

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

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

    protected static ?string $cluster = DailyOpsCluster::class;

    protected static ?string $slug = 'paddle-health';

    protected static ?int $navigationSort = 20;

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

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

    public static function getNavigationLabel(): string
    {
        return __('admin.paddle_health.navigation.label');
    }

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

    public static function getEloquentQuery(): Builder
    {
        $windowStart = now()->subDays(self::TRANSACTION_WINDOW_DAYS);

        return parent::getEloquentQuery()
            ->with(['activeResellerPackage.package'])
            ->withExists('activeResellerPackage as has_active_reseller_package')
            ->addSelect([
                'paddle_customer_duplicates' => Tenant::query()
                    ->selectRaw('count(*)')
                    ->whereColumn('paddle_customer_id', 'tenants.paddle_customer_id')
                    ->whereNotNull('paddle_customer_id'),
            ])
            ->withCount([
                'purchases as paddle_transaction_count' => fn (Builder $query) => $query
                    ->where('provider', 'paddle')
                    ->where('refunded', false),
                'purchases as paddle_transaction_count_window' => fn (Builder $query) => $query
                    ->where('provider', 'paddle')
                    ->where('refunded', false)
                    ->where('purchased_at', '>=', $windowStart),
                'purchases as paddle_refund_count_window' => fn (Builder $query) => $query
                    ->where('provider', 'paddle')
                    ->where('refunded', true)
                    ->where('purchased_at', '>=', $windowStart),
                'checkoutSessions as paddle_checkout_requires_action_count' => fn (Builder $query) => $query
                    ->where('provider', CheckoutSession::PROVIDER_PADDLE)
                    ->where('status', CheckoutSession::STATUS_REQUIRES_CUSTOMER_ACTION),
                'checkoutSessions as paddle_checkout_processing_count' => fn (Builder $query) => $query
                    ->where('provider', CheckoutSession::PROVIDER_PADDLE)
                    ->where('status', CheckoutSession::STATUS_PROCESSING),
                'checkoutSessions as paddle_checkout_expired_count' => fn (Builder $query) => $query
                    ->where('provider', CheckoutSession::PROVIDER_PADDLE)
                    ->whereNotIn('status', [
                        CheckoutSession::STATUS_COMPLETED,
                        CheckoutSession::STATUS_CANCELLED,
                    ])
                    ->whereNotNull('expires_at')
                    ->where('expires_at', '<', now()),
            ])
            ->withSum([
                'purchases as paddle_transaction_total' => fn (Builder $query) => $query
                    ->where('provider', 'paddle')
                    ->where('refunded', false),
            ], 'price')
            ->withSum([
                'purchases as paddle_transaction_total_window' => fn (Builder $query) => $query
                    ->where('provider', 'paddle')
                    ->where('refunded', false)
                    ->where('purchased_at', '>=', $windowStart),
            ], 'price')
            ->withSum([
                'purchases as paddle_refund_total_window' => fn (Builder $query) => $query
                    ->where('provider', 'paddle')
                    ->where('refunded', true)
                    ->where('purchased_at', '>=', $windowStart),
            ], 'price')
            ->withMax([
                'purchases as last_paddle_transaction_at' => fn (Builder $query) => $query
                    ->where('provider', 'paddle'),
            ], 'purchased_at');
    }

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