import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createClient, SupabaseClient } from '@supabase/supabase-js';

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

    onModuleInit(): void {
        const url = this.env.get<string>("SUPABASE_URL");
        const key = this.env.get<string>("SUPABASE_KEY");

        if (!url || !key) {
            this.logger.error("Failed to initialize Supabase");
            throw new Error('Supabase URL and KEY must be set in environment variables');
        }
        this.client = createClient(url, key);
    }

    onModuleDestroy(): void {
        this.logger.log("Supabase client cleanup");
    }

    getClient(): SupabaseClient {
        return this.client;
    }

    async upload(
        bucket: string,
        path: string,
        fileBuffer: Buffer,
        mimetype: string,
    ): Promise<string> {
        const { error } = await this.client.storage.from(bucket).upload(path, fileBuffer, {
            contentType: mimetype,
            upsert: true,
        });

        if (error) {
            this.logger.error(`Failed to upload file: ${error.message}`);
            throw new Error(`Failed to upload file: ${error.message}`);
        }

        const { data } = this.client.storage.from(bucket).getPublicUrl(path);
        this.logger.log(`sucessfully upload file: ${data.publicUrl}`)
        return data.publicUrl;
    }

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