<?php
header('Content-Type: application/json; charset=utf-8');

require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
require_once dirname(__DIR__) . '/includes/api.php';

$songId = isset($_GET['song_id']) ? (int)$_GET['song_id'] : (isset($_GET['id']) ? (int)$_GET['id'] : 0);

if ($songId <= 0) {
    apiError('올바르지 않은 곡 ID입니다.', 'invalid_song_id', 400);
}

try {
    $pdo = getDBConnection();
    $stmt = $pdo->prepare("
        SELECT
            s.id,
            s.title,
            s.artist,
            s.album,
            l.lyrics_text,
            l.updated_at AS lyrics_updated_at
        FROM songs s
        LEFT JOIN lyrics l ON l.song_id = s.id
        WHERE s.id = :song_id AND COALESCE(s.is_missing, 0) = 0
        LIMIT 1
    ");
    $stmt->execute([':song_id' => $songId]);
    $row = $stmt->fetch();

    if (!$row) {
        apiError('곡을 찾을 수 없습니다.', 'song_not_found', 404);
    }

    $lyrics = ensureUtf8String($row['lyrics_text'] ?? '');
    $hasLyrics = trim($lyrics) !== '';
    $data = [
        'id' => (int)$row['id'],
        'song_id' => (int)$row['id'],
        'title' => ensureUtf8String($row['title'] ?? ''),
        'artist' => artistName($row['artist'] ?? ''),
        'album' => albumName($row['album'] ?? ''),
        'lyrics' => $lyrics,
        'has_lyrics' => $hasLyrics,
        'updated_at' => ensureUtf8String($row['lyrics_updated_at'] ?? ''),
    ];

    apiSuccess($data, $hasLyrics ? '' : '등록된 가사가 없습니다.', [], [
        'song_id' => $data['song_id'],
        'title' => $data['title'],
        'artist' => $data['artist'],
        'lyrics' => $data['lyrics'],
        'has_lyrics' => $data['has_lyrics'],
        'updated_at' => $data['updated_at'],
    ]);
} catch (Throwable $e) {
    if (function_exists('writeAppLog')) {
        writeAppLog('error', 'lyrics_error', 'Lyrics load failed', ['song_id' => $songId, 'error' => $e->getMessage()]);
    }
    apiError('가사를 불러오지 못했습니다.', 'server_error', 500);
}
