<?php

namespace App\Domains\Tenant\Controllers;

use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Requests\StoreTenantRequest;
use App\Domains\Tenant\Requests\UpdateTenantRequest;
use App\Domains\Tenant\Resources\TenantResource;
use App\Domains\Tenant\Services\TenantInformationService;
use App\Domains\Tenant\Services\TenantService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;

class TenantController extends Controller
{
    public function __construct(
        protected TenantService $tenantService,
        protected TenantInformationService $tenantInformationService,
    ) {}

    public function index(): JsonResponse
    {
        $tenants = Tenant::query()
            ->latest()
            ->paginateFromRequest();

        $this->tenantInformationService->loadMany($tenants->getCollection());

        return TenantResource::collection($tenants)->response();
    }

    public function store(StoreTenantRequest $request): JsonResponse
    {
        $tenant = $this->tenantService->create($request->validated());

        return TenantResource::make(
            $this->tenantInformationService->load($tenant)
        )->response()->setStatusCode(201);
    }

    public function show(Tenant $tenant): TenantResource
    {
        return TenantResource::make(
            $this->tenantInformationService->load($tenant)
        );
    }

    public function update(UpdateTenantRequest $request, Tenant $tenant): TenantResource
    {
        $tenant = $this->tenantService->update($tenant, $request->validated());

        return TenantResource::make(
            $this->tenantInformationService->load($tenant)
        );
    }

    public function destroy(Tenant $tenant): Response
    {
        $tenant->delete();

        return response()->noContent();
    }
}
