import { google } from 'googleapis';
import * as path from 'path';
import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as os from 'os';

dotenv.config({ path: path.join(__dirname, '../../.env.local') });

// 실제 key 파일 경로에서 로드
const localKeyPath = path.resolve(__dirname, '../../temp.j2h/insuwiki-j2h-902be7d0b6f5.json');

// ADC(Application Default Credentials) 방식으로 강제 주입
process.env.GOOGLE_APPLICATION_CREDENTIALS = localKeyPath;

const getDrive = () => {
    // 키 파일에서 자동으로 읽어옴
    const auth = new google.auth.GoogleAuth({
        scopes: ['https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/drive'], // 파일 쓰기 권한 추가
    });
    return google.drive({ version: 'v3', auth });
};

async function createFolder(drive: ReturnType<typeof getDrive>, name: string, parentId: string) {
    // 1. 이미 존재하는지 확인
    const res = await drive.files.list({
        q: `'${parentId}' in parents and name = '${name}' and mimeType = 'application/vnd.google-apps.folder' and trashed = false`,
        spaces: 'drive',
    });
    if (res.data.files && res.data.files.length > 0) {
        console.log(`📁 [존재] ${name} 폴더 유지`);
        return res.data.files[0].id!;
    }

    // 2. 없으면 생성
    const folderMetadata = {
        name: name,
        mimeType: 'application/vnd.google-apps.folder',
        parents: [parentId]
    };
    const folder = await drive.files.create({
        requestBody: folderMetadata,
        fields: 'id'
    });
    console.log(`✨ [생성] ${name} 폴더`);
    return folder.data.id!;
}

async function uploadDummyPdf(drive: ReturnType<typeof getDrive>, fileName: string, parentId: string) {
    // 1. 이미 존재하는지 확인
    const res = await drive.files.list({
        q: `'${parentId}' in parents and name = '${fileName}' and trashed = false`,
        spaces: 'drive',
    });
    if (res.data.files && res.data.files.length > 0) {
        console.log(`📄 [존재] ${fileName} 유지`);
        return;
    }

    // 빈 더미 PDF 임시 생성
    const tempFilePath = path.join(os.tmpdir(), fileName);
    // 가장 원시적인 형태의 빈 PDF 템플릿
    const dummyPdfContent = `%PDF-1.0\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj\nxref\n0 4\n0000000000 65535 f\n0000000010 00000 n\n0000000053 00000 n\n0000000102 00000 n\ntrailer<</Size 4/Root 1 0 R>>\nstartxref\n149\n%EOF\n`;
    fs.writeFileSync(tempFilePath, dummyPdfContent);

    const fileMetadata = {
        name: fileName,
        parents: [parentId]
    };
    const media = {
        mimeType: 'application/pdf',
        body: fs.createReadStream(tempFilePath)
    };

    await drive.files.create({
        requestBody: fileMetadata,
        media: media,
        fields: 'id'
    });
    console.log(`📝 [업로드] ${fileName}`);
    fs.unlinkSync(tempFilePath); // 임시 파일 삭제
}

async function main() {
    const rootFolderId = process.env.GOOGLE_DRIVE_FOLDER_ID;
    if (!rootFolderId) {
        console.error('❌ GOOGLE_DRIVE_FOLDER_ID 환경 변수 없음');
        process.exit(1);
    }

    console.log('🚀 드라이브 폴더 구조 및 예시 파일 시딩 시작...');
    const drive = getDrive();

    // 1. Root 하위 메인 3개 폴더 생성
    const termsFolderId = await createFolder(drive, '01_약관', rootFolderId);
    const newsletterFolderId = await createFolder(drive, '02_소식지', rootFolderId);
    const tableFolderId = await createFolder(drive, '03_보험료테이블', rootFolderId);

    // [약관] 폴더 트리 생성
    const lifeFolderId = await createFolder(drive, '생명보험', termsFolderId);
    const samsungFolderId = await createFolder(drive, '삼성생명', lifeFolderId);
    await uploadDummyPdf(drive, '삼성생명_퍼펙트종신_2403.pdf', samsungFolderId);
    await uploadDummyPdf(drive, '삼성생명_통합프리미어종신_2311.pdf', samsungFolderId);

    const dbLifeFolderId = await createFolder(drive, 'DB생명', lifeFolderId);
    await uploadDummyPdf(drive, 'DB생명_백년친구내가고른건강_2401.pdf', dbLifeFolderId);

    const nonLifeFolderId = await createFolder(drive, '손해보험', termsFolderId);
    const hyundaiFolderId = await createFolder(drive, '현대해상', nonLifeFolderId);
    await uploadDummyPdf(drive, '현대해상_무배당퍼펙트플러스종합_2501.pdf', hyundaiFolderId);

    // [소식지] 더미 파일 업로드
    await uploadDummyPdf(drive, '메리츠화재_알파Plus소식지_2502.pdf', newsletterFolderId);

    // [보험료테이블] 더미 파일 업로드
    await uploadDummyPdf(drive, '한화생명_시그니처암_환급률표_2310.pdf', tableFolderId);


    console.log('\n✅ 폴더 구조 생성 및 더미 PDF 업로드 완료!');
}

main().catch(console.error);
