<?php

namespace App\Http\Controllers\Api\V1\Design;

use App\Helpers\ApiResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\Design\BomTemplate\CloneRequest;
use App\Http\Requests\Design\BomTemplate\DiffRequest;
use App\Http\Requests\Design\BomTemplate\ReplaceItemsRequest;
use App\Http\Requests\Design\BomTemplate\UpsertRequest;
use App\Services\Design\BomTemplateService;

class BomTemplateController extends Controller
{
    public function __construct(
        protected BomTemplateService $service
    ) {}

    public function listByVersion(int $versionId)
    {
        return ApiResponse::handle(function () use ($versionId) {
            // 내부에서 tenant 스코프 처리
            return $this->service->paginate($versionId, page: 1, size: PHP_INT_MAX)->items();
        }, __('message.fetched'));
    }

    public function upsertTemplate(UpsertRequest $request, int $versionId)
    {
        return ApiResponse::handle(function () use ($request, $versionId) {
            $payload = $request->validated();

            return $this->service->upsertTemplate(
                modelVersionId: $versionId,
                name: $payload['name'] ?? 'Main',
                isPrimary: (bool) ($payload['is_primary'] ?? true),
                notes: $payload['notes'] ?? null
            );
        }, __('message.created'));
    }

    public function show(int $templateId)
    {
        return ApiResponse::handle(fn () => $this->service->show($templateId, true), __('message.fetched'));
    }

    public function replaceItems(ReplaceItemsRequest $request, int $templateId)
    {
        return ApiResponse::handle(function () use ($request, $templateId) {
            $payload = $request->validated();
            $this->service->replaceItems($templateId, $payload['items']);

            return null;
        }, __('message.bom.bulk_upsert'));
    }

    public function diff(int $templateId, DiffRequest $request)
    {
        return ApiResponse::handle(function () use ($templateId, $request) {
            $otherId = $request->validated()['other_template_id'];

            return $this->service->diffTemplates($templateId, $otherId);
        }, __('message.design.template_diff'));
    }

    public function cloneTemplate(int $templateId, CloneRequest $request)
    {
        return ApiResponse::handle(function () use ($templateId, $request) {
            $payload = $request->validated();
            $tpl = $this->service->cloneTemplate(
                templateId: $templateId,
                targetVersionId: $payload['target_version_id'] ?? null,
                name: $payload['name'] ?? null,
                isPrimary: (bool) ($payload['is_primary'] ?? false),
                notes: $payload['notes'] ?? null
            );

            return $tpl;
        }, __('message.design.template_cloned'));
    }
}
