<?php

namespace Inside\BCLH\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Inside\Authentication\Models\User;
use Inside\BCLH\Jobs\GenerateBulkCSV;
use Inside\BCLH\Jobs\ImportBulkCSV;
use Inside\Content\Services\Queries\ContentQuery;

/**
 * Bulk update controller
 *
 * @category Class
 * @author   Maecia <technique@maecia.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.maecia.com/
 */
class BulkCSVController
{
    public function export(Request $request): JsonResponse
    {
        $request->merge(
            [
                'fields' => json_encode(['uuid', 'content_type']),
            ]
        );

        /** @var string $filters */
        $filters = $request->get('filters');
        $filters = json_decode($filters, true);

        $filters['status:eq'] = 1;
        $types = ['sops', 'rops', 'documents'];

        if (array_key_exists('uuid:in', $filters)) {
            unset($filters['folders']);
            $types[] = 'declined_documents';
            $request['filters'] = json_encode($filters);
        }

        $contentQueryService = new ContentQuery();
        $contentQueryService->requestQuery(implode(',', $types), $request);
        $contents = $contentQueryService->transformCollection()['data'];

        /** @var User $user */
        $user = Auth::user();
        Queue::push(new GenerateBulkCSV($user->uuid, $contents, array_key_exists('uuid:in', $filters)));

        return response()->json(['success' => true]);
    }

    public function import(Request $request): JsonResponse
    {
        /** @var string $filePath */
        $filePath = $request->input('file');

        if (! Storage::exists($filePath)) {
            abort(400, 'Invalid argument: file \''.$filePath.'\' does not exist');
        }

        /** @var User $user */
        $user = Auth::user();
        Queue::push(new ImportBulkCSV($user->uuid, $filePath));

        return response()->json(['success' => true]);
    }
}
