<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use App\Models\License;
use App\Models\ProductVersion;
use App\Services\Security\AuditService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class DownloadsController extends Controller
{
    public function __construct(private AuditService $audit) {}

    public function index()
    {
        // All active licenses the customer can download
        $licenses = auth()->user()->licenses()
            ->with(['product.latestVersion', 'product.versions' => fn($q) => $q->stable()->latest()->take(1)])
            ->where('status', 'active')
            ->latest()
            ->get();

        // Download history
        $history = auth()->user()->downloads()
            ->with(['product', 'version'])
            ->latest('created_at')
            ->take(20)
            ->get();

        return view('customer.downloads.index', compact('licenses', 'history'));
    }

    public function download(Request $request, License $license)
    {
        abort_if($license->user_id !== auth()->id(), 403);
        abort_unless($license->isValid(), 403, 'License is not active.');

        $version = $request->version
            ? $license->product->versions()->where('version', $request->version)->firstOrFail()
            : $license->product->latestVersion;

        abort_if(! $version || ! $version->file_path, 404, 'No file available.');
        abort_unless(Storage::disk('local')->exists($version->file_path), 404);

        \App\Models\Download::create([
            'user_id'            => auth()->id(),
            'license_id'         => $license->id,
            'product_id'         => $license->product_id,
            'product_version_id' => $version->id,
            'ip_address'         => $request->ip(),
            'user_agent'         => $request->userAgent(),
            'created_at'         => now(),
        ]);

        $version->increment('download_count');
        $this->audit->log('license.download', $license, [], ['version' => $version->version]);

        return Storage::disk('local')->download(
            $version->file_path,
            $license->product->slug . '-' . $version->version . '.zip'
        );
    }
}
