<?php

namespace App\Services\ItemMaster;

use App\Models\ItemMaster\CustomTab;
use App\Services\Service;
use Illuminate\Database\Eloquent\Collection;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class CustomTabService extends Service
{
    /**
     * 커스텀 탭 목록
     */
    public function index(): Collection
    {
        $tenantId = $this->tenantId();

        return CustomTab::with('columnSetting')
            ->where('tenant_id', $tenantId)
            ->orderBy('order_no')
            ->get();
    }

    /**
     * 커스텀 탭 생성
     */
    public function store(array $data): CustomTab
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        $maxOrder = CustomTab::where('tenant_id', $tenantId)
            ->max('order_no');

        $tab = CustomTab::create([
            'tenant_id' => $tenantId,
            'label' => $data['label'],
            'icon' => $data['icon'] ?? null,
            'is_default' => $data['is_default'] ?? false,
            'order_no' => ($maxOrder ?? -1) + 1,
            'created_by' => $userId,
        ]);

        return $tab->load('columnSetting');
    }

    /**
     * 커스텀 탭 수정
     */
    public function update(int $id, array $data): CustomTab
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        $tab = CustomTab::where('tenant_id', $tenantId)
            ->where('id', $id)
            ->first();

        if (! $tab) {
            throw new NotFoundHttpException(__('error.not_found'));
        }

        $tab->update([
            'label' => $data['label'] ?? $tab->label,
            'icon' => $data['icon'] ?? $tab->icon,
            'is_default' => $data['is_default'] ?? $tab->is_default,
            'updated_by' => $userId,
        ]);

        return $tab->load('columnSetting');
    }

    /**
     * 커스텀 탭 삭제
     */
    public function destroy(int $id): void
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        $tab = CustomTab::where('tenant_id', $tenantId)
            ->where('id', $id)
            ->first();

        if (! $tab) {
            throw new NotFoundHttpException(__('error.not_found'));
        }

        $tab->update(['deleted_by' => $userId]);
        $tab->delete();
    }

    /**
     * 커스텀 탭 순서 변경
     */
    public function reorder(array $items): void
    {
        $tenantId = $this->tenantId();
        $userId = $this->apiUserId();

        foreach ($items as $item) {
            CustomTab::where('tenant_id', $tenantId)
                ->where('id', $item['id'])
                ->update([
                    'order_no' => $item['order_no'],
                    'updated_by' => $userId,
                ]);
        }
    }
}
