<?php

namespace App\Http\Controllers;

use App\Enums\DataExportScope;
use App\Models\DataExport;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class ProfileController extends Controller
{
    public function index(Request $request): Response
    {
        $user = $request->user()
            ->load(['tenant' => function ($query) {
                $query->with([
                    'purchases' => fn ($purchases) => $purchases
                        ->with('package')
                        ->latest('purchased_at')
                        ->limit(10),
                    'tenantPackages' => fn ($packages) => $packages
                        ->with('package')
                        ->orderByDesc('active')
                        ->orderByDesc('purchased_at'),
                ]);
            }]);

        $tenant = $user->tenant;
        $activePackage = $tenant?->tenantPackages
            ?->first(fn ($package) => (bool) $package->active);

        $purchases = $tenant?->purchases
            ?->map(fn ($purchase) => [
                'id' => $purchase->id,
                'packageName' => $purchase->package?->getNameForLocale(app()->getLocale())
                    ?? $purchase->package?->name
                    ?? __('Unknown package'),
                'price' => $purchase->price !== null ? (float) $purchase->price : null,
                'purchasedAt' => optional($purchase->purchased_at)->toIso8601String(),
                'type' => $purchase->type,
                'provider' => $purchase->provider,
            ])
            ->values()
            ->all();

        $recentExports = $user->dataExports()
            ->where('scope', DataExportScope::USER->value)
            ->latest()
            ->limit(5)
            ->get()
            ->map(fn ($export) => [
                'id' => $export->id,
                'status' => $export->status,
                'size' => $export->size_bytes,
                'expires_at' => optional($export->expires_at)->toIso8601String(),
                'created_at' => optional($export->created_at)->toIso8601String(),
                'download_url' => $export->isReady() && ! $export->hasExpired()
                    ? route('profile.data-exports.download', $export)
                    : null,
                'error_message' => $export->error_message,
            ]);

        $pendingExport = $user->dataExports()
            ->where('scope', DataExportScope::USER->value)
            ->whereIn('status', [
                DataExport::STATUS_PENDING,
                DataExport::STATUS_PROCESSING,
            ])
            ->exists();

        $lastReadyExport = $user->dataExports()
            ->where('scope', DataExportScope::USER->value)
            ->where('status', DataExport::STATUS_READY)
            ->latest('created_at')
            ->first();

        $nextExportAt = $lastReadyExport?->created_at?->clone()->addDay();

        return Inertia::render('Profile/Index', [
            'userData' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'username' => $user->username,
                'preferredLocale' => $user->preferred_locale,
                'emailVerifiedAt' => optional($user->email_verified_at)->toIso8601String(),
                'mustVerifyEmail' => $user instanceof MustVerifyEmail,
            ],
            'tenant' => $tenant ? [
                'id' => $tenant->id,
                'name' => $tenant->name,
                'subscriptionStatus' => $tenant->subscription_status,
                'subscriptionExpiresAt' => optional($tenant->subscription_expires_at)->toIso8601String(),
                'activePackage' => $activePackage ? [
                    'name' => $activePackage->package?->getNameForLocale(app()->getLocale())
                        ?? $activePackage->package?->name
                        ?? __('Unknown package'),
                    'price' => $activePackage->price !== null ? (float) $activePackage->price : null,
                    'expiresAt' => optional($activePackage->expires_at)->toIso8601String(),
                    'remainingEvents' => $activePackage->remaining_events ?? null,
                ] : null,
            ] : null,
            'purchases' => $purchases,
            'dataExport' => [
                'exports' => $recentExports,
                'hasPending' => $pendingExport,
                'nextRequestAt' => $nextExportAt?->toIso8601String(),
            ],
        ]);
    }
}
