<?php

namespace App\Http\Controllers;

use App\Helpers\EntryHelpers;
use App\Models\EntryFile;
use App\Models\LogXfUser;
use App\Services\FileServersService;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class FileServerController extends Controller {

    public function __construct(private FileServersService $fs) {}

    /**
     * @throws ConnectionException
     */
    public function uploadChunk(Request $request, string $section): JsonResponse {
        $request->validate([
            'file' => 'required|file',
            'file_uuid' => 'required|string|max:128',
            'current_chunk' => 'required|integer|min:0',
            'total_chunks' => 'required|integer|min:1',
            'filename' => 'required|string|max:255',
        ]);

        $type = $section;
        $fileUuid = $request->input('file_uuid');
        $currentChunk = (int) $request->input('current_chunk');
        $totalChunks = (int) $request->input('total_chunks');
        $filename = $request->input('filename');

        $data = $this->fs->uploadChunk(
            $request->file('file'),
            $fileUuid,
            $currentChunk,
            $totalChunks,
            $filename,
            $type
        );

        if( !isset( $data['file'] ) || $data['file'] === false ){
            $data['finished'] = false;
            return response()->json($data);
        }

        $fileData = [
            'uuid' => $fileUuid,
            'type' => $type,
            'filename' => $filename,
            'filepath' => $data['file_path'],
            'filesize' => $data['file']['size'],
            'favorite_server' => $data['favorite_server'],
            'favorite_at' => time(),
            'state' => 'public',
        ];

        activity('entry-file')
            ->causedBy(LogXfUser::find(\Auth::user()->getAuthIdentifier()))
            ->withProperties($fileData)
            ->event('file_upload')
            ->log("File uploaded")
        ;

        \Cache::put("uploaded_file_{$fileUuid}", $fileData, now()->addHours(2) );

        $data['finished'] = true;
        return response()->json($data);

    }

    public function download(Request $request, int $entry_id, EntryFile $file ) {

        if( $file->entry_id != $entry_id ) {
            abort(404);
        }

        if($request->input('count_download', true)) {
            if (!EntryHelpers::fileAlreadyDownloaded($file)) {
                EntryHelpers::markFileAsDownloaded($file);
                $file->increaseDownloadCount();
            }
        }

        return redirect( $this->fs->getDownloadFileUrl( $file) );
    }
}
