import { HeadBucketCommand, PutObjectCommand, S3Client } from "@aws-sdk/client-s3";
import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";

@Injectable()
export class S3Service implements OnModuleInit, OnModuleDestroy {
    constructor(private readonly env: ConfigService) { }
    private readonly logger = new Logger(S3Service.name)
    private s3Client: S3Client;


    async onModuleInit(): Promise<void> {
        const endpoint = this.env.get<string>("S3_ENDPOINT");
        const accessKeyId = this.env.get<string>("S3_ACCESS_KEY");
        const secretAccessKey = this.env.get<string>("S3_SECRET_KEY");

        if (!endpoint || !accessKeyId || !secretAccessKey) {
            this.logger.error("Failed to initialize S3 Storage");
            throw new Error("Environment Not Found.");
        }

        try {
            this.s3Client = new S3Client({
                region: "",
                endpoint,
                credentials: {
                    accessKeyId,
                    secretAccessKey,
                },
                forcePathStyle: true,
            });

            this.logger.log("S3 Storage connected successfully");
        } catch (e) {
            this.logger.error("Failed to initialize S3 Storage", e);
            throw e;
        }
    }
    onModuleDestroy(): void {
        this.logger.log("S3 Storage Client Cleanup")
    }

    getClient(): S3Client {
        return this.s3Client
    }

    async isBucketExists(): Promise<void> {
        try {
            await this.s3Client.send(new HeadBucketCommand({
                Bucket: 'KPDH'
            }))
            this.logger.log("Storage Bucket KPDH Exists")
        } catch (e) {
            if (e.$metadata?.httpStatusCode === 404) {
                const msg = "KPDH Bucket Not Found"
                throw new Error(msg)
            }

            if (e.$metadata?.httpStatusCode === 403) {
                const msg = "No permission to access the KPDH bucket. Check credentials/ACL."
                throw new Error(msg)
            }
            throw e
        }
    }

    async upload(bucket: string, path: string, fileBuffer: Buffer, mimeType: string): Promise<string> {
        try {
            await this.isBucketExists()
            const upload = new PutObjectCommand({
                Bucket: bucket,
                Key: path,
                Body: fileBuffer,
                ContentType: mimeType,
                ACL: 'public-read'
            })

            await this.s3Client.send(upload)
            const result = `${this.env.get<string>("S3_ENDPOINT")}/${bucket}/${path}`;

            this.logger.log(`Upload Sucessfully : ${result}`)
            return result

        } catch (e) {
            throw new Error(`Failed to upload file: ${e.message}`);
        }
    }

    generatePath(folder: string, userId: string, filename: string): string {
        return `${folder}/${userId}-${filename}`;
    }

}

