<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\Upload;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class UploadController extends Controller
{
    private array $allowedMimes = [
        'application/zip',
        'application/octet-stream',
        'application/x-zip-compressed',
    ];

    public function index()
    {
        if (!auth()->user()->isAdmin()) {
            return response()->json(['success' => false, 'message' => 'Forbidden'], 403);
        }
        $uploads = Upload::with('uploader')->latest()->paginate(20);
        return response()->json(['success' => true, 'data' => $uploads]);
    }

    public function store(Request $request)
    {
        if (!auth()->user()->isOwner()) {
            return response()->json(['success' => false, 'message' => 'Only owners can upload files'], 403);
        }

        $request->validate([
            'file'    => 'required|file|max:51200', // 50MB max
            'version' => 'nullable|string|max:20',
            'notes'   => 'nullable|string|max:500',
        ]);

        $file = $request->file('file');

        // Validate MIME type
        if (!in_array($file->getMimeType(), $this->allowedMimes)) {
            return response()->json(['success' => false, 'message' => 'Only ZIP files are allowed'], 415);
        }

        // Store outside public directory
        $storedName = Str::uuid() . '.' . $file->getClientOriginalExtension();
        $path       = $file->storeAs('uploads', $storedName, 'local');

        $upload = Upload::create([
            'original_name' => $file->getClientOriginalName(),
            'stored_name'   => $storedName,
            'path'          => $path,
            'mime_type'     => $file->getMimeType(),
            'size'          => $file->getSize(),
            'uploaded_by'   => auth()->id(),
            'version'       => $request->version,
            'notes'         => $request->notes,
        ]);

        AuditLog::record('UPLOAD_FILE', "Uploaded {$upload->original_name} v{$upload->version}");

        return response()->json(['success' => true, 'upload' => $upload], 201);
    }

    public function download(Upload $upload)
    {
        if (!auth()->user()->isAdmin()) {
            return response()->json(['success' => false, 'message' => 'Forbidden'], 403);
        }
        AuditLog::record('DOWNLOAD_FILE', "Downloaded {$upload->original_name}");
        return response()->download(storage_path("app/{$upload->path}"), $upload->original_name);
    }

    public function destroy(Upload $upload)
    {
        if (!auth()->user()->isOwner()) {
            return response()->json(['success' => false, 'message' => 'Forbidden'], 403);
        }
        \Storage::disk('local')->delete($upload->path);
        AuditLog::record('DELETE_FILE', "Deleted {$upload->original_name}");
        $upload->delete();
        return response()->json(['success' => true, 'message' => 'File deleted']);
    }
}
