|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | +import fs from "fs/promises"; |
| 3 | +import path from "path"; |
| 4 | +import { generationDb } from "../../../../lib/jsondb"; |
| 5 | +import { validatePresetWithArtist } from "../../../../lib/public/schemas/preset"; |
| 6 | +import { validateArtist } from "../../../../lib/public/schemas/artist"; |
| 7 | +import { createSlug } from "../../../../lib/utils/create-slug"; |
| 8 | +import { createPresetSlugBase } from "lib/utils/urls"; |
| 9 | +import { Preset } from "lib/public/interface"; |
| 10 | + |
| 11 | +interface CreatePresetRequest { |
| 12 | + generationId: string; |
| 13 | + artistId?: number | null; |
| 14 | + newArtist?: { |
| 15 | + title: string; |
| 16 | + description: string; |
| 17 | + } | null; |
| 18 | + song: string; |
| 19 | + part: string; |
| 20 | + imageUrl?: string | null; |
| 21 | + tabsUrl?: string; |
| 22 | + pickup: { |
| 23 | + type: string; |
| 24 | + tone: number; |
| 25 | + position: string; |
| 26 | + }; |
| 27 | +} |
| 28 | + |
| 29 | +export async function POST(request: NextRequest) { |
| 30 | + try { |
| 31 | + const body: CreatePresetRequest = await request.json(); |
| 32 | + |
| 33 | + // Валидация входных данных |
| 34 | + if (!body.generationId) { |
| 35 | + return NextResponse.json( |
| 36 | + { error: "Generation ID is required" }, |
| 37 | + { status: 400 }, |
| 38 | + ); |
| 39 | + } |
| 40 | + if (!body.song || !body.song.trim()) { |
| 41 | + return NextResponse.json( |
| 42 | + { error: "Song name is required" }, |
| 43 | + { status: 400 }, |
| 44 | + ); |
| 45 | + } |
| 46 | + if (!body.part || !body.part.trim()) { |
| 47 | + return NextResponse.json( |
| 48 | + { error: "Song part is required" }, |
| 49 | + { status: 400 }, |
| 50 | + ); |
| 51 | + } |
| 52 | + if ( |
| 53 | + !body.artistId && |
| 54 | + (!body.newArtist || !body.newArtist.title || !body.newArtist.title.trim()) |
| 55 | + ) { |
| 56 | + return NextResponse.json( |
| 57 | + { error: "Artist ID or new artist data is required" }, |
| 58 | + { status: 400 }, |
| 59 | + ); |
| 60 | + } |
| 61 | + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
| 62 | + if (!body.pickup?.type?.trim()) { |
| 63 | + return NextResponse.json( |
| 64 | + { error: "Pickup type is required" }, |
| 65 | + { status: 400 }, |
| 66 | + ); |
| 67 | + } |
| 68 | + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
| 69 | + if (!body.pickup?.tone || body.pickup.tone < 1 || body.pickup.tone > 10) { |
| 70 | + return NextResponse.json( |
| 71 | + { error: "Pickup tone must be between 1 and 10" }, |
| 72 | + { status: 400 }, |
| 73 | + ); |
| 74 | + } |
| 75 | + |
| 76 | + // Получаем генерацию |
| 77 | + const generation = await generationDb.getGenerationById(body.generationId); |
| 78 | + if (!generation) { |
| 79 | + return NextResponse.json( |
| 80 | + { error: "Generation not found" }, |
| 81 | + { status: 404 }, |
| 82 | + ); |
| 83 | + } |
| 84 | + |
| 85 | + // Получаем последнюю версию chain |
| 86 | + if (generation.versions.length === 0) { |
| 87 | + return NextResponse.json( |
| 88 | + { error: "Generation has no versions" }, |
| 89 | + { status: 400 }, |
| 90 | + ); |
| 91 | + } |
| 92 | + const latestVersion = generation.versions[generation.versions.length - 1]; |
| 93 | + if (!latestVersion) { |
| 94 | + return NextResponse.json( |
| 95 | + { error: "Latest version not found" }, |
| 96 | + { status: 400 }, |
| 97 | + ); |
| 98 | + } |
| 99 | + const latestChain = latestVersion.chain; |
| 100 | + |
| 101 | + // Читаем существующие данные |
| 102 | + const presetsPath = path.join(process.cwd(), "data", "presets.json"); |
| 103 | + const artistsPath = path.join(process.cwd(), "data", "artists.json"); |
| 104 | + |
| 105 | + const [presetsData, artistsData] = await Promise.all([ |
| 106 | + fs.readFile(presetsPath, "utf-8").then((data) => JSON.parse(data)), |
| 107 | + fs.readFile(artistsPath, "utf-8").then((data) => JSON.parse(data)), |
| 108 | + ]); |
| 109 | + |
| 110 | + let artist; |
| 111 | + let artistId: number; |
| 112 | + |
| 113 | + // Обрабатываем артиста |
| 114 | + if (body.newArtist) { |
| 115 | + // Создаем нового артиста |
| 116 | + const maxId = Math.max( |
| 117 | + ...(artistsData as Array<{ id: number }>).map((a) => a.id), |
| 118 | + 0, |
| 119 | + ); |
| 120 | + artistId = maxId + 1; |
| 121 | + |
| 122 | + artist = { |
| 123 | + id: artistId, |
| 124 | + title: body.newArtist.title.trim(), |
| 125 | + slug: createSlug(body.newArtist.title.trim()), |
| 126 | + description: |
| 127 | + body.newArtist.description.trim() || |
| 128 | + `Описание для ${body.newArtist.title.trim()}`, |
| 129 | + }; |
| 130 | + |
| 131 | + // Валидируем нового артиста |
| 132 | + validateArtist(artist); |
| 133 | + |
| 134 | + // Добавляем в массив артистов |
| 135 | + artistsData.push(artist); |
| 136 | + } else { |
| 137 | + // Используем существующего артиста |
| 138 | + artistId = body.artistId as number; |
| 139 | + artist = ( |
| 140 | + artistsData as Array<{ |
| 141 | + id: number; |
| 142 | + title: string; |
| 143 | + slug: string; |
| 144 | + description: string; |
| 145 | + }> |
| 146 | + ).find((a) => a.id === artistId); |
| 147 | + if (!artist) { |
| 148 | + return NextResponse.json( |
| 149 | + { error: "Artist not found" }, |
| 150 | + { status: 404 }, |
| 151 | + ); |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + const presetId = generation.id; |
| 156 | + |
| 157 | + const song = body.song.trim(); |
| 158 | + const part = body.part.trim(); |
| 159 | + const slug = createPresetSlugBase(song, part); |
| 160 | + |
| 161 | + // Проверяем уникальность комбинации slug + artistId |
| 162 | + const existingPreset = ( |
| 163 | + presetsData as Array<{ |
| 164 | + slug: string; |
| 165 | + origin: { artistId: number }; |
| 166 | + }> |
| 167 | + ).find( |
| 168 | + (preset) => preset.slug === slug && preset.origin.artistId === artistId, |
| 169 | + ); |
| 170 | + |
| 171 | + if (existingPreset) { |
| 172 | + return NextResponse.json( |
| 173 | + { |
| 174 | + error: `Preset with slug "${slug}" for artist ID ${String(artistId)} already exists`, |
| 175 | + details: { |
| 176 | + slug, |
| 177 | + artistId, |
| 178 | + artistTitle: artist.title, |
| 179 | + }, |
| 180 | + }, |
| 181 | + { status: 409 }, |
| 182 | + ); |
| 183 | + } |
| 184 | + |
| 185 | + // Создаем объект пресета |
| 186 | + const preset = { |
| 187 | + id: presetId, |
| 188 | + origin: { |
| 189 | + artistId: artistId, |
| 190 | + song: song, |
| 191 | + part: part, |
| 192 | + imageUrl: body.imageUrl?.trim() || null, |
| 193 | + }, |
| 194 | + description: generation.proDescription.sound_description, |
| 195 | + chain: latestChain, |
| 196 | + pickup: { |
| 197 | + type: body.pickup.type.trim(), |
| 198 | + tone: body.pickup.tone, |
| 199 | + position: body.pickup.position, |
| 200 | + }, |
| 201 | + slug: slug, |
| 202 | + tabsUrl: body.tabsUrl?.trim() || undefined, |
| 203 | + }; |
| 204 | + |
| 205 | + // Создаем объект для валидации с полным артистом |
| 206 | + const presetWithArtist: Preset = { |
| 207 | + id: preset.id, |
| 208 | + origin: { |
| 209 | + artist: artist, |
| 210 | + song: preset.origin.song, |
| 211 | + part: preset.origin.part, |
| 212 | + imageUrl: preset.origin.imageUrl, |
| 213 | + }, |
| 214 | + description: preset.description, |
| 215 | + chain: preset.chain, |
| 216 | + // @ts-expect-error this is fine |
| 217 | + pickup: preset.pickup, |
| 218 | + slug: preset.slug, |
| 219 | + tabsUrl: preset.tabsUrl, |
| 220 | + }; |
| 221 | + |
| 222 | + // Валидируем пресет |
| 223 | + validatePresetWithArtist(presetWithArtist); |
| 224 | + |
| 225 | + // Добавляем пресет в массив |
| 226 | + presetsData.push(preset); |
| 227 | + |
| 228 | + // Сохраняем файлы |
| 229 | + await Promise.all([ |
| 230 | + fs.writeFile(presetsPath, JSON.stringify(presetsData, null, 2), "utf-8"), |
| 231 | + fs.writeFile(artistsPath, JSON.stringify(artistsData, null, 2), "utf-8"), |
| 232 | + ]); |
| 233 | + |
| 234 | + console.log(`✅ Пресет создан: ${presetId} для артиста ${artist.title}`); |
| 235 | + |
| 236 | + return NextResponse.json({ |
| 237 | + success: true, |
| 238 | + presetId: presetId, |
| 239 | + presetSlug: slug, |
| 240 | + artistSlug: artist.slug, |
| 241 | + message: "Preset created successfully", |
| 242 | + }); |
| 243 | + } catch (error) { |
| 244 | + console.error("Error creating preset:", error); |
| 245 | + |
| 246 | + if (error instanceof Error) { |
| 247 | + // Если это ошибка валидации Zod |
| 248 | + if (error.message.includes("validation")) { |
| 249 | + return NextResponse.json( |
| 250 | + { error: `Validation error: ${error.message}` }, |
| 251 | + { status: 400 }, |
| 252 | + ); |
| 253 | + } |
| 254 | + return NextResponse.json({ error: error.message }, { status: 500 }); |
| 255 | + } |
| 256 | + |
| 257 | + return NextResponse.json( |
| 258 | + { error: "Internal server error" }, |
| 259 | + { status: 500 }, |
| 260 | + ); |
| 261 | + } |
| 262 | +} |
0 commit comments