<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class FileUploadController extends BaseApiController
{
    public function upload(Request $request): JsonResponse
    {
        $request->validate([
            'file' => 'required|file|mimes:pdf,doc,docx,xls,xlsx,jpg,jpeg,png|max:10240',
            'type' => 'in:document,image,other',
        ]);

        $file = $request->file('file');
        $type = $request->type ?? 'document';
        $path = "uploads/{$type}/" . now()->format('Y/m') . '/' . Str::uuid() . '.' . $file->getClientOriginalExtension();

        Storage::disk('public')->putFileAs(
            dirname($path),
            $file,
            basename($path)
        );

        $url = Storage::disk('public')->url($path);

        activity('uploads')->causedBy($request->user())->log("Ficheiro carregado: {$file->getClientOriginalName()}");

        return $this->successResponse([
            'url'       => $url,
            'name'      => $file->getClientOriginalName(),
            'size_kb'   => round($file->getSize() / 1024, 1),
            'type'      => $file->getMimeType(),
            'extension' => $file->getClientOriginalExtension(),
        ], 'Ficheiro carregado com sucesso', 201);
    }
}
