<?php

namespace App\Http\Controllers;

use App\Models\Clan;
use App\Models\EthnicGroup;
use Illuminate\Http\Request;

class EthnicLookupController extends Controller
{
    public function groups(Request $request)
    {
        $data = $request->validate([
            'country' => ['required','string','max:3'],
        ]);
        $list = EthnicGroup::query()
            ->where('country_code', strtoupper($data['country']))
            ->orderBy('name')
            ->get(['id','name','languages'])
            ->map(fn($g) => [
                'id' => $g->id,
                'name' => $g->name,
                'languages' => $g->languages,
            ]);
        return response()->json($list);
    }

    public function clans(Request $request)
    {
        $data = $request->validate([
            'ethnic_group_id' => ['required','integer','exists:ethnic_groups,id'],
        ]);
        $gid = (int) $data['ethnic_group_id'];
        $list = Clan::query()
            ->where(function($q) use ($gid){
                $q->where('ethnic_group_id', $gid)
                  ->orWhereHas('ethnicGroups', function($r) use ($gid){ $r->where('ethnic_group_id', $gid); });
            })
            ->orderBy('name')
            ->get(['id','name'])
            ->map(fn($c) => [ 'id' => $c->id, 'name' => $c->name ]);
        return response()->json($list);
    }
}
