<?php

namespace Maestro\Core\Http\Controllers;

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

class OrganizationController extends Controller
{
    /** Current user's organization profile (TLP-aligned field names). */
    public function show(Request $request): JsonResponse
    {
        abort_unless($request->user()?->can('settings.organization.view'), 403);

        $organization = $request->user()?->organization;

        abort_if(! $organization, 404);

        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 = $request->user()?->organization;

        abort_if(! $organization, 404);

        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()));
    }

    private function present(Organization $organization): array
    {
        $payload = $organization->toArray();
        $payload['company_name'] = $organization->company_name ?: $organization->name;

        return $payload;
    }
}
