<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\CreateCompanyRequest;
use App\Models\Company;
use App\Services\CompanyService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Validation\ValidationException;

class CompanyController extends Controller
{
    public function __construct(
        private readonly CompanyService $companyService
    ) {}

    /**
     * Store a newly created company with its admin.
     */
    public function store(CreateCompanyRequest $request): JsonResponse
    {
        try {
            $company = $this->companyService->createCompanyWithAdmin($request->validated());

            return response()->json([
                'success' => true,
                'message' => 'Company created successfully. Invitation email sent.',
                'data' => [
                    'id' => $company->id,
                    'name' => $company->name,
                    'email' => $company->email,
                    'status' => $company->status,
                    'created_at' => $company->created_at->toIso8601String(),
                ],
            ], 201);
        } catch (ValidationException $e) {
            throw $e;
        } catch (\Exception $e) {
            Log::error('Error creating company: ' . $e->getMessage(), [
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->validated(),
            ]);
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while creating the company.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Display a listing of companies (paginated).
     */
    public function index(): JsonResponse
    {
        try {
            $perPage = (int) request()->input('per_page', 15);
            $perPage = min(max($perPage, 1), 100); // Between 1 and 100

            $companies = $this->companyService->getAllCompanies($perPage);

            return response()->json([
                'success' => true,
                'data' => $companies->items() ? collect($companies->items())->map(fn ($company) => [
                    'id' => $company->id,
                    'name' => $company->name,
                    'email' => $company->email,
                    'phone' => $company->phone,
                    'status' => $company->status,
                    'portal_users_count' => $company->portal_users_count,
                    'created_at' => $company->created_at->toIso8601String(),
                ]) : [],
                'pagination' => [
                    'current_page' => $companies->currentPage(),
                    'last_page' => $companies->lastPage(),
                    'per_page' => $companies->perPage(),
                    'total' => $companies->total(),
                    'from' => $companies->firstItem() ?? 0,
                    'to' => $companies->lastItem() ?? 0,
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching companies: ' . $e->getMessage(), [
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching companies.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }

    /**
     * Display the specified company.
     */
    public function show(Company $company): JsonResponse
    {
        try {
            $company = $this->companyService->getCompanyDetails($company);

            return response()->json([
                'success' => true,
                'data' => [
                    'id' => $company->id,
                    'name' => $company->name,
                    'email' => $company->email,
                    'phone' => $company->phone,
                    'rc_number' => $company->rc_number,
                    'address' => $company->address,
                    'city' => $company->city,
                    'state' => $company->state,
                    'country' => $company->country,
                    'insurance_type' => $company->insurance_type,
                    'registration_date' => $company->registration_date,
                    'license_number' => $company->license_number,
                    'status' => $company->status,
                    'employees_count' => $company->employees_count,
                    'admins' => $company->portalUsers->map(fn ($user) => [
                        'id' => $user->id,
                        'name' => $user->name,
                        'email' => $user->email,
                        'password_set' => $user->hasSetPassword(),
                    ]),
                    'created_at' => $company->created_at->toIso8601String(),
                    'updated_at' => $company->updated_at->toIso8601String(),
                ],
            ]);
        } catch (\Exception $e) {
            Log::error('Error fetching specific company: ' . $e->getMessage(), [
                'exception' => $e,
                'trace' => $e->getTraceAsString(),
            ]);
            return response()->json([
                'success' => false,
                'message' => 'An error occurred while fetching the company.',
                'error' => config('app.debug') ? $e->getMessage() : 'Internal server error',
            ], 500);
        }
    }
}
