<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Requests\API\Library\CreateOrUpdateRequest;
use App\Http\Resources\API\LibraryResource;
use App\Models\Library;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LibraryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(CreateOrUpdateRequest $request)
    {
        Library::query()->create([
            ...$request->all(),
            'created_by' => Auth::id(),
            'company_id' => Auth::user()->company_id,
            'whitelist' => $request->whitelist ? sprintf(",%s", implode(',', $request->whitelist)) : null,
        ]);

        return $this->created();
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        $library = Library::query()->findOrFail($id);

        return new LibraryResource($library);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $library = Library::query()->findOrFail($id);

        $library->fill($request->only([
            'name', 'acl', 'asset_id', 'project_id',
        ]));
        $library->whitelist = $request->whitelist ? sprintf(",%s", implode(',', $request->whitelist)) : null;

        $library->save();

        return $this->noContent();
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}