<?php

namespace App\Master\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Resources\ContentSyncResource;
use App\Master\ContentSyncRepository;
use App\Master\Http\Requests\ContentSyncDataRequest;
use App\Master\Http\Requests\ContentSyncRequest;
use App\Master\Http\Requests\CreateContentSyncRequest;
use App\Master\Http\Requests\UpdateContentSyncRequest;
use App\Models\ContentSync;
use Illuminate\Http\Request;

class ContentSyncController extends Controller
{
    public function index()
    {
        return ContentSync::query()
            ->with([
                'user',
                'tenant',
            ])
            ->latest()
            ->paginate();
    }

    public function show(ContentSync $contentSync)
    {
        return new ContentSyncResource($contentSync);
    }

    public function store(CreateContentSyncRequest $request, ContentSyncRepository $repository)
    {
        if (in_array($request->input('direction'), [ContentSync::PROVIDE, ContentSync::RECEIVE])) {
            $token =  $repository->provideToken($request->input());
            return \response([
                'status' => 'ok',
                'id' => $token->id,
            ]);
        }

        return response($repository->attemptSync($request->input()));
    }

    public function getRemoteEntries(Request $request, ContentSyncRepository $repository)
    {
        return $repository->pullDataFromRemote($request->input());
    }

    public function provideEntries(ContentSyncDataRequest $request, ContentSyncRepository $repository)
    {
        tenancy()->initialize($request->sync()->tenant_id);
        $data = $repository->provideData($request->input());
        tenancy()->end();
        return response($data);
    }

    public function update(Request $request, ContentSync $sync)
    {
        $sync->update([
            'data' => collect($request->input('data'))
                ->pluck('data')
                ->toArray(),
        ]);
        return new ContentSyncResource($sync);
    }

    public function receiveDataFromRemote(ContentSyncRequest $request)
    {
        $details = $request->sync()->details ?? [];
        $details['scope'] = $request->input('scope');
        $request->sync()
            ->update([
                'details' => $details,
                'data' => $request->input('data'),
            ]);
        return response('Data received');
    }

    public function run(Request $request, ContentSyncRepository $repository)
    {
        $details = $request->input('details', []);
        $details['tenant_id'] = $request->input('tenant_id');
        return $repository->importData($details, $request->input('data'));
    }

    public function renewToken(
        UpdateContentSyncRequest $request,
        ContentSyncRepository $repository,
        ContentSync $sync
    ): ContentSyncResource {
        $sync = $repository->renewToken($sync);
        return new ContentSyncResource($sync);
    }
}
