<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Module;
use App\Services\System\UpdateService;
use Laracasts\Flash\Flash;

class AdminMarketplaceController extends Controller
{
    public function index(UpdateService $updateService)
    {
        $title = 'Module Marketplace';

        $catalogResponse = $updateService->getCatalog();
        $catalogStatus   = $catalogResponse['status'] ?? 'ok';
        $updateCache     = $updateService->getModuleUpdateCache();
        $installed       = Module::all()->keyBy('slug');

        $modules = collect($catalogResponse['modules'] ?? [])
            ->keyBy('slug')
            ->map(function (array $item, string $slug) use ($installed, $updateCache) {
                $local          = $installed->get($slug);
                $cached         = $updateCache[$slug] ?? [];
                $isInstalled    = $local !== null;
                $latestVersion  = $item['latest_version'] ?? null;
                $installedVer   = $local?->version;

                $updateAvailable = $isInstalled
                    && $latestVersion
                    && $installedVer
                    && version_compare($latestVersion, $installedVer, '>');

                return [
                    'slug'               => $slug,
                    'name'               => $item['name'],
                    'description'        => $item['description'],
                    'icon_url'           => $item['icon_url'] ?? null,
                    'price'              => $item['price'],
                    'is_free'            => $item['is_free'],
                    'is_entitled'        => $item['is_entitled'],
                    'support_active'     => $item['support_active'],
                    'support_expires_at' => $item['support_expires_at'] ?? null,
                    'latest_version'     => $latestVersion,
                    'buy_url'            => $item['buy_url'],
                    'is_installed'       => $isInstalled,
                    'is_active'          => $isInstalled && $local->isActive(),
                    'installed_version'  => $installedVer,
                    'update_available'   => $updateAvailable,
                    'download_url'       => $cached['download_url'] ?? null,
                    'checksum'           => $cached['checksum'] ?? null,
                    'changelog'          => $cached['changelog'] ?? null,
                    'module_id'          => $local?->id,
                    'state'              => $this->resolveState($item, $local, $updateAvailable),
                ];
            })
            ->values();

        return view('admin.marketplace.index', compact('title', 'modules', 'catalogStatus'));
    }

    public function refresh(UpdateService $updateService)
    {
        $updateService->getCatalog(force: true);

        Flash::success('Module catalog refreshed.');

        return redirect()->route('ch-admin.marketplace.index');
    }

    private function resolveState(array $catalog, ?Module $local, bool $updateAvailable): string
    {
        if (! $catalog['is_entitled']) {
            return 'not_owned';
        }

        if ($local && ! $catalog['support_active']) {
            return 'support_expired';
        }

        if ($local && $updateAvailable) {
            return 'update_available';
        }

        if ($local?->isActive()) {
            return 'installed_active';
        }

        if ($local && ! $local->isActive()) {
            return 'installed_inactive';
        }

        return $catalog['is_free'] ? 'free_available' : 'purchased_available';
    }
}
