import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Drive from '@ioc:Adonis/Core/Drive'
import OSS from 'ali-oss'
import Env from '@ioc:Adonis/Core/Env'
import * as console from 'node:console'

class FilesService {
    private client: OSS

    constructor() {
        this.client = new OSS({
            region: Env.get('OSS_REGION'),
            accessKeyId: Env.get('OSS_KEY'),
            accessKeySecret: Env.get('OSS_SECRET'),
            bucket: Env.get('OSS_BUCKET')
        })
    }

    public async generateThumbnailUrl(
        filePath: string,
        width: number = 300,
        expires: number = 600
    ): Promise<string> {
        try {
            // const exists = await Drive.exists(filePath)
            // if (!exists) {
            //     throw new Error('文件不存在')
            // }

            return this.client.signatureUrl(filePath, {
                expires,
                process: `image/resize,w_${width}`
            })
        } catch (error) {
            throw new Error(`生成缩略图URL失败: ${error.message}`)
        }
    }

    public async batchDelete(filePaths: string[]) {
        if (!Array.isArray(filePaths) || filePaths.length === 0) {
            throw new Error('请提供要删除的文件路径数组')
        }

        const results = {
            success: [] as string[],
            failed: [] as { path: string; error: string }[]
        }

        // 删除
        for (const filePath of filePaths) {
            try {
                const exists = await Drive.exists(filePath)

                if (!exists) {
                    results.failed.push({
                        path: filePath,
                        error: '文件不存在'
                    })
                    continue
                }

                await Drive.delete(filePath)
                results.success.push(filePath)
            } catch (error) {
                results.failed.push({
                    path: filePath,
                    error: error.message || '删除失败'
                })
            }
        }

        return results
    }
}

export default new FilesService()
