<?php

namespace Controllers;

use Libs\MultipartFormDataParser;
use Libs\ResponseLib;
use Models\DocumentModel;
use Psr\Http\Message\ServerRequestInterface;
use Services\DocumentStorageService;

class DocumentUploadController
{
    private DocumentModel $documentModel;
    private DocumentStorageService $storage;
    private int $maxUploadBytes;

    public function __construct()
    {
        $this->documentModel = new DocumentModel();
        $this->storage = new DocumentStorageService();
        $this->maxUploadBytes = 30 * 1024 * 1024;
    }

    public function __invoke(ServerRequestInterface $request)
    {
        $userId = (int)($request->getAttribute('api_user_id') ?? 0);
        $companyId = (int)($request->getAttribute('api_company_id') ?? 0);

        if ($userId <= 0 || $companyId <= 0) {
            return ResponseLib::sendFail('Unauthorized', [], 'E_VALIDATE')->withStatus(401);
        }

        $contentLength = (int)$request->getHeaderLine('Content-Length');
        if ($contentLength > 0 && $contentLength > $this->maxUploadBytes) {
            return ResponseLib::sendFail('File too large. Max 30MB.', [], 'E_TOO_LARGE')->withStatus(413);
        }

        try {
            $parsed = MultipartFormDataParser::parse($request);
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Invalid multipart form-data: ' . $e->getMessage(), [], 'E_VALIDATE')->withStatus(400);
        }

        $fields = $parsed['fields'] ?? [];
        $files = $parsed['files'] ?? [];

        $documentType = isset($fields['document_type']) ? (string)$fields['document_type'] : '';
        if ($documentType === '') {
            return ResponseLib::sendFail('Missing field: document_type', [], 'E_VALIDATE')->withStatus(400);
        }

        $file = $files['file'] ?? null;
        if (!is_array($file) || !isset($file['content'])) {
            return ResponseLib::sendFail('Missing file field: file', [], 'E_VALIDATE')->withStatus(400);
        }

        $originalFilename = (string)($file['filename'] ?? 'upload.bin');
        $contentType = (string)($file['content_type'] ?? 'application/octet-stream');
        $content = (string)$file['content'];

        if (strlen($content) > $this->maxUploadBytes) {
            return ResponseLib::sendFail('File too large. Max 30MB.', [], 'E_TOO_LARGE')->withStatus(413);
        }

        try {
            $documentType = $this->storage->sanitizeDocumentType($documentType);
            $dir = $this->storage->ensureDirectory($companyId, $userId, $documentType);
            $storedFilename = $this->storage->buildStoredFilename($originalFilename, $contentType);
            $storedPath = $this->storage->writeFile($dir, $storedFilename, $content);

            $created = $this->documentModel->create($userId, $documentType, $storedPath);

            return ResponseLib::sendOk($created, 'S_CREATED');
        } catch (\Throwable $e) {
            return ResponseLib::sendFail('Upload failed: ' . $e->getMessage(), [], 'E_INTERNAL')->withStatus(500);
        }
    }
}
