<?php

namespace App\Http\Controllers\Api\V1\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\V1\Tenant\RegisterBusinessRequest;
use App\Http\Resources\Api\V1\TenantResource;
use App\Http\Resources\Api\V1\UserResource;
use App\Services\ResponseService;
use App\Services\TenantService;
use App\Support\ModuleRegistry;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

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

    /**
     * POST /auth/register-business
     * Public endpoint — registers a new business + owner account.
     */
    public function registerBusiness(RegisterBusinessRequest $request): JsonResponse
    {
        try {
            $result = $this->tenantService->registerBusiness($request->validated());

            return $this->responseService->created([
                'tenant' => new TenantResource($result['tenant']),
                'user'   => new UserResource($result['user']),
                'token'  => $result['token'],
            ], 'Business registered successfully');
        } catch (\Exception $e) {
            return $this->responseService->serverError(
                'Business registration failed',
                $e->getMessage()
            );
        }
    }

    /**
     * GET /tenant
     * Returns the current tenant info (modules, settings, business type).
     */
    public function current(Request $request): JsonResponse
    {
        try {
            if (!app()->bound('current_tenant')) {
                return $this->responseService->notFound('No tenant context found');
            }

            $tenant = app('current_tenant')->load('branches');

            return $this->responseService->success(
                new TenantResource($tenant),
                'Tenant retrieved successfully'
            );
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to retrieve tenant', $e->getMessage());
        }
    }

    /**
     * PUT /tenant/settings
     * Update tenant-level settings (currency, timezone, tax, etc.)
     */
    public function updateSettings(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'currency' => ['nullable', 'string', 'max:10'],
                'timezone' => ['nullable', 'string', 'max:60'],
                'tax_rate' => ['nullable', 'numeric', 'min:0', 'max:100'],
                'tax_type' => ['nullable', 'string', 'in:inclusive,exclusive'],
            ]);

            $tenant = app('current_tenant');
            $tenant = $this->tenantService->updateSettings($tenant, $request->only([
                'currency', 'timezone', 'tax_rate', 'tax_type',
            ]));

            return $this->responseService->success(
                new TenantResource($tenant),
                'Settings updated successfully'
            );
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to update settings', $e->getMessage());
        }
    }

    /**
     * POST /tenant/modules/{module}/toggle
     * Enable or disable a module for the current tenant.
     */
    public function toggleModule(Request $request, string $module): JsonResponse
    {
        try {
            $request->validate([
                'enabled' => ['required', 'boolean'],
            ]);

            if (!in_array($module, ModuleRegistry::allModuleKeys(), true)) {
                return $this->responseService->error('Invalid module name', 422);
            }

            $tenant = app('current_tenant');
            $tenant = $this->tenantService->toggleModule($tenant, $module, $request->boolean('enabled'));

            return $this->responseService->success(
                new TenantResource($tenant),
                'Module updated successfully'
            );
        } catch (\Exception $e) {
            return $this->responseService->serverError('Failed to toggle module', $e->getMessage());
        }
    }

    /**
     * GET /tenant/modules
     * Returns all available modules and whether each is enabled.
     */
    public function modules(Request $request): JsonResponse
    {
        $tenant  = app()->bound('current_tenant') ? app('current_tenant') : null;
        $enabled = $tenant ? ($tenant->enabled_modules ?? []) : [];

        $modules = collect(ModuleRegistry::MODULES)->map(function ($label, $key) use ($enabled) {
            return [
                'key'     => $key,
                'label'   => $label,
                'enabled' => in_array($key, $enabled, true),
            ];
        })->values();

        return $this->responseService->success($modules, 'Modules retrieved successfully');
    }
}
