<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\ProjectResource;
use App\Http\Support\ApiInputMapper;
use App\Models\Project;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Http\Response;

class ProjectController extends Controller
{
    public function categories(): JsonResponse
    {
        return response()->json(config('project_categories'));
    }

    public function index(): AnonymousResourceCollection
    {
        $projects = Project::query()->with('client')->orderByDesc('created_at')->get();

        return ProjectResource::collection($projects);
    }

    public function show(Project $project): ProjectResource
    {
        $project->load('client');

        return new ProjectResource($project);
    }

    public function store(Request $request): JsonResponse
    {
        $data = ApiInputMapper::project($request->all());
        $project = Project::query()->create($data);
        $project->load('client');

        return (new ProjectResource($project))
            ->response()
            ->setStatusCode(Response::HTTP_CREATED);
    }

    public function update(Request $request, Project $project): ProjectResource
    {
        $data = ApiInputMapper::projectPartial($request->all());
        if ($data !== []) {
            $project->fill($data);
            $project->save();
        }
        $project->load('client');

        return new ProjectResource($project->fresh());
    }

    public function destroy(Project $project): JsonResponse
    {
        $project->delete();

        return response()->json(['message' => 'Project deleted']);
    }
}
