<?php

namespace Maestro\Core\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maestro\Core\Models\Organization;

class OrganizationController extends Controller
{
    /**
     * Singleton company profile for this deployment (see {@see Organization::instance()}).
     */
    public function show(Request $request): JsonResponse
    {
        abort_unless($request->user()?->can('settings.organization.view'), 403);

        $organization = Organization::instance();

        abort_if(! $organization, 404, 'No organization profile row. Run database seeders or insert one organization.');

        return response()->json($this->present($organization));
    }

    public function update(Request $request): JsonResponse
    {
        abort_unless($request->user()?->can('settings.organization.edit'), 403);

        $validated = $request->validate([
            // TLP-aligned
            'company_name' => ['sometimes', 'required', 'string', 'max:255'],
            'street' => ['nullable', 'string', 'max:255'],
            'house_number' => ['nullable', 'string', 'max:255'],
            'postal_code' => ['nullable', 'string', 'max:255'],
            'city' => ['nullable', 'string', 'max:255'],
            'country' => ['nullable', 'string', 'max:255'],
            'website' => ['nullable', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'email' => ['nullable', 'email', 'max:255'],
            'invoice_email' => ['nullable', 'email', 'max:255'],
            'kvk_number' => ['nullable', 'string', 'max:50'],
            'vat_number' => ['nullable', 'string', 'max:50'],
            'iban' => ['nullable', 'string', 'max:50'],
            'contact_name' => ['nullable', 'string', 'max:255'],
            // Legacy aliases
            'name' => ['sometimes', 'string', 'max:255'],
            'address_line_1' => ['nullable', 'string', 'max:255'],
            'address_line_2' => ['nullable', 'string', 'max:255'],
            'region' => ['nullable', 'string', 'max:120'],
            'country_code' => ['nullable', 'string', 'max:8'],
        ]);

        $organization = Organization::instance();

        abort_if(! $organization, 404, 'No row in organizations table. Seed or create one profile for this deployment.');

        if (array_key_exists('company_name', $validated)) {
            $trimmed = trim((string) ($validated['company_name'] ?? ''));
            if ($trimmed !== '') {
                $validated['company_name'] = $trimmed;
                $validated['name'] = $trimmed;
            }
        }

        $organization->update($validated);

        return response()->json($this->present($organization->fresh()));
    }

    /**
     * @return array<string, mixed>
     */
    private function present(Organization $organization): array
    {
        $payload = $organization->toArray();
        $payload['company_name'] = $organization->company_name ?: $organization->name;

        return $payload;
    }
}
