<?php

namespace App\Http\Controllers\Api\PublicApi;

use App\Http\Controllers\Controller;
use App\Http\Resources\CompanyResource;
use App\Models\Company;


class CompanyController extends Controller
{
    /**
     * Sistemdeki onaylı/aktif firmaların hafif listesi (transfer sihirbazının
     * "firma seç" adımı + genel firma seçiciler için).
     */
    public function index()
    {
        $companies = Company::query()
            ->approved()
            ->active()
            ->orderBy('name')
            ->get(['id', 'name', 'slug', 'logo', 'city', 'country']);

        return response()->json(['data' => $companies]);
    }

    public function show(string $slug)
    {
        $company = Company::query()
            ->where('slug', $slug)
            ->approved()
            ->active()
            ->with([
                'consultants' => fn ($query) => $query
                    ->active()
                    ->with('user:id,name')
                    ->withCount([
                        'listings as published_listings_count' => fn ($q) => $q->where('status', 'published'),
                    ])
                    ->latest('id'),
                
                'listings' => fn ($query) => $query
                    ->where('listings.status', 'published')
                    ->with(['category', 'coverImage', 'featureValues.feature', 'consultantProfile'])
                    ->latest('listings.published_at'),
            ])
            ->withCount([
                'consultants' => fn ($q) => $q->active(),
                'listings' => fn ($q) => $q->where('listings.status', 'published'),
            ])
            ->firstOrFail();

        return new CompanyResource($company);
    }
}
