import { loadEnv } from 'vite'
import archiver from 'archiver'
import fs from 'fs'
import OSS from 'ali-oss'
import { format } from 'date-fns'
import { Buffer } from 'node:buffer'
import COS from 'cos-nodejs-sdk-v5'

async function ossUpload(filePath, version) {
    let client = new OSS({
        accessKeyId: 'PXzJyah5rZfWHIIH',
        accessKeySecret: 'e1MS6j0wypXJrw8CM0hObZu8qKbfah',
        region: 'oss-cn-hangzhou',
        bucket: 'zm-shorts'
    })
    let { url } = await client.put(`packages/${format(new Date(), 'yyyyMMddHHmmss')}.zip`, filePath, {
        headers: {
            'x-oss-object-acl': 'public-read'
        }
    })
    url = url.replace('http://', 'https://')
    console.log('package uploaded: %s', url.replace('http://', 'https://'))
    await client.put('packages/meta.json', Buffer.from(JSON.stringify({ url, version: version })), {
        headers: { 'x-oss-object-acl': 'public-read' }
    })
}

async function cosUpload(filePath, version) {
    var cos = new COS({
        SecretId: 'IKIDhOGOYkw59GUh0FMONLJKPLGfzJ5oeaWO',
        SecretKey: 'sfSC9ACC9zjVK7BMUew8SmEdtBgDi6dI'
    })
    const url = await new Promise((resolve, reject) => {
        cos.putObject(
            {
                Bucket: 'duanju2-1321229830',
                Region: 'ap-jakarta',
                Key: `packages/${format(new Date(), 'yyyyMMddHHmmss')}.zip`,
                StorageClass: 'STANDARD',
                Body: fs.createReadStream(filePath),
                ACL: 'public-read'
            },
            function (err, data) {
                if (err) reject(err)
                else resolve('https://' + data.Location)
            }
        )
    })
    console.log('package uploaded: %s', url)
    await new Promise((resolve, reject) => {
        cos.putObject(
            {
                Bucket: 'duanju2-1321229830',
                Region: 'ap-jakarta',
                Key: 'packages/meta.json',
                StorageClass: 'STANDARD',
                Body: Buffer.from(JSON.stringify({ url, version: version })),
                ACL: 'public-read'
            },
            function (err, data) {
                if (err) reject(err)
                else resolve(data)
            }
        )
    })
}

export default function VitePluginUploadPackage() {
    let mode = ''
    let env = {}
    return {
        name: 'upload-package',
        config(config, { command }) {
            mode = config.mode
            env = loadEnv(mode, process.cwd())
        },
        async buildStart(options) {
            if (env['VITE_APP'] !== 'true') return
            const meta = JSON.parse(fs.readFileSync('./src/plugins/updater_meta.json'))
            meta.version++
            fs.writeFileSync('./src/plugins/updater_meta.json', JSON.stringify(meta))
        },
        async closeBundle(options) {
            if (env['VITE_APP'] !== 'true') return
            const meta = JSON.parse(fs.readFileSync('./src/plugins/updater_meta.json'))

            const sourceDir = 'dist'
            const outputFilePath = 'dist.zip'

            await new Promise((resolve, reject) => {
                const output = fs.createWriteStream(outputFilePath)
                output.on('close', function () {
                    resolve()
                })
                const archive = archiver('zip')
                archive.pipe(output)
                archive.directory(sourceDir, false)
                archive.finalize()
            }).catch(e => {
                console.log(e)
            })
            switch (env['VITE_STORAGE_TYPE']) {
                case 'oss':
                    await ossUpload(outputFilePath, meta.version)
                    break
                case 'cos':
                    await cosUpload(outputFilePath, meta.version)
                    break
            }
        }
    }
}
