<?php

namespace App\Http\Controllers\Api\V1;

use App\Helpers\ApiResponse;
use App\Models\Products\CommonCode;
use App\Models\Scopes\TenantScope;
use Illuminate\Http\Request;

class CommonController
{
    public static function getComeCode()
    {
        return ApiResponse::handle(function () {
            return CommonCode::query()
                ->select(['code_group', 'code', 'name', 'description', 'is_active'])
                ->get();
        }, '공통코드');
    }

    public function list(Request $request)
    {
        return ApiResponse::handle(function () {
            // Service implementation needed
            return [];
        }, __('message.fetched'));
    }

    /**
     * 특정 그룹의 공통 코드 목록 조회
     *
     * GET /api/v1/settings/common/{group}
     */
    public function index(Request $request, string $group)
    {
        return ApiResponse::handle(function () use ($group) {
            $tenantId = app('tenant_id');

            // BelongsToTenant 스코프 해제 (글로벌 폴백 로직 직접 처리)
            $base = CommonCode::withoutGlobalScope(TenantScope::class)
                ->where('code_group', $group)
                ->where('is_active', true);

            // 테넌트 전용 데이터가 있으면 테넌트만, 없으면 글로벌 폴백
            $hasTenantData = (clone $base)->where('tenant_id', $tenantId)->exists();

            return (clone $base)
                ->select(['id', 'code', 'name', 'description', 'sort_order', 'attributes'])
                ->where(function ($query) use ($tenantId, $hasTenantData) {
                    if ($hasTenantData) {
                        $query->where('tenant_id', $tenantId);
                    } else {
                        $query->whereNull('tenant_id');
                    }
                })
                ->orderBy('sort_order')
                ->get();
        }, __('message.fetched'));
    }

    public function store(Request $request)
    {
        return ApiResponse::handle(function () {
            // Service implementation needed
            return [];
        }, __('message.settings.common_code_saved'));
    }

    public function update(Request $request, int $id)
    {
        return ApiResponse::handle(function () {
            // Service implementation needed
            return [];
        }, __('message.updated'));
    }

    public function destroy(Request $request, int $id)
    {
        return ApiResponse::handle(function () {
            // Service implementation needed
            return [];
        }, __('message.deleted'));
    }
}
