package firebase

import (
	"context"
	"fmt"
	"io"
	"net/url"

	firebase "firebase.google.com/go"
)

type StorageService interface {
	UploadFile(ctx context.Context, file io.Reader, fileName string, contentType string) (string, error)
}

type storageService struct {
	app    *firebase.App
	bucket string
}

func NewStorageService(app *firebase.App, bucket string) StorageService {
	return &storageService{
		app:    app,
		bucket: bucket,
	}
}

func (s *storageService) UploadFile(ctx context.Context, file io.Reader, fileName string, contentType string) (string, error) {
	client, err := s.app.Storage(ctx)
	if err != nil {
		return "", fmt.Errorf("error getting storage client: %v", err)
	}

	bucket, err := client.Bucket(s.bucket)
	if err != nil {
		return "", fmt.Errorf("error getting bucket: %v", err)
	}

	object := bucket.Object(fileName)
	wc := object.NewWriter(ctx)
	wc.ContentType = contentType

	if _, err := io.Copy(wc, file); err != nil {
		return "", fmt.Errorf("error copying file to bucket: %v", err)
	}
	if err := wc.Close(); err != nil {
		return "", fmt.Errorf("error closing writer: %v", err)
	}

	// Make the object public or generate a signed URL.
	// For simplicity and matching user request "publicURL", we'll make it public if possible or use the standard GCS URL.
	// Firebase Storage files are usually accessible via: https://firebasestorage.googleapis.com/v0/b/<bucket>/o/<encoded-path>?alt=media

	publicURL := fmt.Sprintf("https://firebasestorage.googleapis.com/v0/b/%s/o/%s?alt=media",
		s.bucket, url.QueryEscape(fileName))

	return publicURL, nil
}
