<?php

namespace App\Http\Controllers\Api;

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

class DomainController extends Controller
{
    public function index(): AnonymousResourceCollection
    {
        $domains = Domain::query()->with('server')->orderBy('expiration_date')->get();

        return DomainResource::collection($domains);
    }

    public function show(Domain $domain): DomainResource
    {
        $domain->load('server');

        return new DomainResource($domain);
    }

    public function store(Request $request): JsonResponse
    {
        $data = ApiInputMapper::domain($request->all());
        $domain = Domain::query()->create($data);
        $domain->load('server');

        return (new DomainResource($domain))
            ->response()
            ->setStatusCode(Response::HTTP_CREATED);
    }

    public function update(Request $request, Domain $domain): DomainResource
    {
        $data = ApiInputMapper::domain($request->all());
        $domain->update($data);
        $domain->load('server');

        return new DomainResource($domain->fresh());
    }

    public function destroy(Domain $domain): JsonResponse
    {
        $domain->delete();

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