// src/routes/api/upload/+server.ts

import { error, json } from '@sveltejs/kit';
import fs from 'fs/promises';
import path from 'path';
import { promisify } from 'util';
import { exec } from 'child_process';
import pool from '$lib/server/database'; // ✅ DB 풀 임포트

const execAsync = promisify(exec);

export async function POST({ request }) {
  try {
    const formData = await request.formData();
    const file = formData.get('video') as File | null;
    const originalFileName = formData.get('fileName') as string | null;

    if (!file || !originalFileName) {
      throw error(400, '필수 데이터가 누락되었습니다.');
    }

    // --- 1. 파일 저장 ---
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');
    const dateFolder = `${year}${month}${day}`;

    const baseDir = '/workspace/image/movie'; 
    const uploadDir = path.join(baseDir, dateFolder);
    await fs.mkdir(uploadDir, { recursive: true });

    const filePath = path.join(uploadDir, originalFileName);
    const buffer = Buffer.from(await file.arrayBuffer());
    await fs.writeFile(filePath, buffer);

    console.log(`파일 저장 완료: ${filePath}`);

    // --- ✅ 2. FFprobe로 TotalFrameCount 계산 ---
    const ffprobeCommand = `ffprobe -v error -select_streams v:0 -count_frames -show_entries stream=nb_read_frames -of default=nokey=1:noprint_wrappers=1 "${filePath}"`;
    const { stdout } = await execAsync(ffprobeCommand);
    const totalFrameCount = parseInt(stdout.trim(), 10);

    if (isNaN(totalFrameCount)) {
        throw new Error('프레임 수를 계산할 수 없습니다.');
    }
    console.log(`프레임 수 계산 완료: ${totalFrameCount}`);

    // --- ✅ 3. PostgreSQL에 데이터 INSERT ---
    const locationNetwork = 'localhost'; // 예시 IP, 실제 환경에 맞게 수정 필요
    const locationFile = originalFileName;
    const objectType = 0;
    
    const queryText = `
        INSERT INTO public."TumerMovie" ("LocationNetwork", "LocationFile", "TotalFrameCount", "ObjectType")
        VALUES ($1, $2, $3, $4)
    `;
    const queryValues = [locationNetwork, locationFile, totalFrameCount, objectType];

    await pool.query(queryText, queryValues);
    console.log(`데이터베이스 저장 완료: ${locationFile}`);


    // --- 4. 성공 응답 반환 ---
    return json({ 
        success: true, 
        filePath,
        db_inserted: true,
        frameCount: totalFrameCount
    });

  } catch (err) {
    console.error('파일 업로드 및 DB 처리 오류:', err);
    throw error(500, '서버 처리 중 오류가 발생했습니다.');
  }
}