<?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\Container;
use App\Models\Enums\LibraryType;
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(Request $request)
    {
        $libraries = Library::query()->filter($request->all())->allowed()->get(['id', 'name']);

        $containerCount = Container::query()->allowed()
            ->whereIn("library_id", $libraries->pluck("id")->toArray())
            ->selectRaw("count(*) as cut, library_id")
            ->groupBy("library_id")
            ->pluck("cut", "library_id");

        $libraries = $libraries->map(function (Library $library) use ($containerCount) {
            $library->itemCount = $containerCount->get($library->id, 0);
            $library->type = 'library';
            $library->uniId = $library->type . '_' . $library->id;
            return $library;
        });

        return $this->success([
            'data' => $libraries
        ]);
    }

    /**
     * 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::allowed()->findOrFail($id);

        return new LibraryResource($library);
    }

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

        if ($library->container()->count() > 0) {
            return $this->badRequest("The container has been associated and is not allowed to be deleted");
        }

        $library->delete();

        return $this->noContent();
    }

    public function linkage(Request $request, string $type)
    {
        $libraryType = LibraryType::from($type);
        if (in_array($libraryType->value, [LibraryType::PROJECT->value, LibraryType::ASSET->value]) && !$request->get("id")) {
            return $this->badRequest("Parameter ID cannot be empty");
        }

        $where = match ($libraryType) {
            LibraryType::ASSET => ['asset_id' => $request->get("id")],
            LibraryType::PROJECT => ['project_id' => $request->get("id")],
            LibraryType::CUSTOM => []
        };

        $libraries = Library::query()
            ->allowed()
            ->where("type", $type)->when($where, fn($query) => $query->where($where))
            ->get(['id', 'name'])
            ->each(function ($libraries) {
            // 设置固定的type值
            $libraries->type = 'library';
            $libraries->uniId=$libraries->type.'_'.$libraries->id;
            });

        return $this->success([
            'data' => $libraries
        ]);
    }
}