import { LabelClass } from '@/types' import { USE_MOCK_DATA } from '@/app/constants' import { getColorForClass } from '@/utils/colors' import { api, delay } from './api' import { getMockDb, saveMockDb } from './mockData' import { getProjectById } from './projectService' export async function getLabels(projectId: string): Promise { if (!USE_MOCK_DATA) { const project = await getProjectById(projectId) return project.classes } await delay(80) const db = getMockDb() const project = db.projects.find((p) => p.id === projectId || p.slug === projectId) return project ? project.classes : db.projects[0]?.classes ?? [] } export async function replaceLabels( projectId: string, classes: LabelClass[] ): Promise { const { data } = await api.put(`/projects/${projectId}/classes`, classes) return data.map((c: any, i: number) => ({ id: c.id, name: c.name, color: c.color, count: 0, shortcutKey: String(i + 1), })) } export async function createLabel( projectId: string, input: { name: string; color?: string } ): Promise { if (!USE_MOCK_DATA) { const existing = await getLabels(projectId) const next: LabelClass = { id: `cls-new-${Date.now()}`, name: input.name.trim(), color: input.color || getColorForClass(existing.length), count: 0, shortcutKey: String(existing.length + 1), } const replaced = await replaceLabels(projectId, [...existing, next]) const created = replaced.find((c) => c.name === next.name) ?? replaced[replaced.length - 1]! return created } await delay(140) const db = getMockDb() const project = db.projects.find((p) => p.id === projectId || p.slug === projectId) if (!project) { throw new Error(`Không tìm thấy dự án: ${projectId}`) } const nextShortcut = String(project.classes.length + 1) const newLabel: LabelClass = { id: `cls-${Date.now()}`, name: input.name.trim(), color: input.color || getColorForClass(project.classes.length), count: 0, shortcutKey: project.classes.length < 9 ? nextShortcut : undefined, } project.classes.push(newLabel) saveMockDb(db) return newLabel } export async function deleteLabel(projectId: string, labelId: string): Promise { if (!USE_MOCK_DATA) { const existing = await getLabels(projectId) await replaceLabels( projectId, existing.filter((c) => c.id !== labelId) ) return } await delay(120) const db = getMockDb() const project = db.projects.find((p) => p.id === projectId || p.slug === projectId) if (!project) return project.classes = project.classes.filter((c) => c.id !== labelId) saveMockDb(db) }