<?php

namespace App\Domains\Tenant\Controllers\AdminApp;

use App\Domains\Auth\Models\User;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Requests\AdminApp\UpdateWebsiteExtraRequest;
use App\Domains\Tenant\Resources\AdminApp\WebsiteExtrasResource;
use App\Domains\Tenant\Services\TenantInformationService;
use App\Domains\Tenant\Services\WebsiteExtraService;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class WebsiteExtraController extends Controller
{
    public function __construct(
        protected WebsiteExtraService $websiteExtraService,
        protected TenantInformationService $tenantInformationService,
    ) {}

    public function show(Request $request): WebsiteExtrasResource
    {
        return WebsiteExtrasResource::make(
            $this->loadTenant($request->user())
        );
    }

    public function update(
        UpdateWebsiteExtraRequest $request,
        string $websiteExtraCode
    ): WebsiteExtrasResource {
        $tenant = $request->user()->tenant()->firstOrFail();

        $this->websiteExtraService->updateForTenant(
            $tenant,
            $websiteExtraCode,
            $request->validated('config')
        );

        return WebsiteExtrasResource::make(
            $this->loadTenant($request->user())
        );
    }

    public function toggle(Request $request, string $websiteExtraCode): WebsiteExtrasResource
    {
        $tenant = $request->user()->tenant()->firstOrFail();

        $this->websiteExtraService->toggleForTenant($tenant, $websiteExtraCode);

        return WebsiteExtrasResource::make(
            $this->loadTenant($request->user())
        )->additional([
            'code' => 'tenant.website_extra_toggled',
            'message' => __('api.tenant.website_extra_toggled'),
        ]);
    }

    private function loadTenant(User $user): Tenant
    {
        $tenant = $user->tenant()->firstOrFail();

        return $this->tenantInformationService->load($tenant, [
            'websiteType.extras',
        ]);
    }
}
