<?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\TenantService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;

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

    public function index(): JsonResponse
    {
        return TenantResource::collection(
            Tenant::query()
                ->with(['headerLogo', 'footerLogo', 'mainCarouselImages', 'socialMedia'])
                ->latest()
                ->paginateFromRequest()
        )->response();
    }

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

        return TenantResource::make(
            $tenant->loadMissing(['headerLogo', 'footerLogo', 'mainCarouselImages', 'socialMedia'])
        )->response()->setStatusCode(201);
    }

    public function show(Tenant $tenant): TenantResource
    {
        return TenantResource::make(
            $tenant->loadMissing(['headerLogo', 'footerLogo', 'mainCarouselImages', 'socialMedia'])
        );
    }

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

        return TenantResource::make(
            $tenant->loadMissing(['headerLogo', 'footerLogo', 'mainCarouselImages', 'socialMedia'])
        );
    }

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

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