package org

import (
	"context"

	"go.b0esche.cloud/backend/internal/database"

	"github.com/google/uuid"
)

// ResolveUserOrgs returns the organizations a user belongs to
func ResolveUserOrgs(ctx context.Context, db *database.DB, userID uuid.UUID) ([]database.Organization, error) {
	return db.GetUserOrganizations(ctx, userID)
}

// CheckMembership checks if user is member of org and returns role
func CheckMembership(ctx context.Context, db *database.DB, userID, orgID uuid.UUID) (string, error) {
	membership, err := db.GetUserMembership(ctx, userID, orgID)
	if err != nil {
		return "", err
	}
	return membership.Role, nil
}

// CreateOrg creates a new organization and adds the user as owner
func CreateOrg(ctx context.Context, db *database.DB, userID uuid.UUID, name, slug string) (*database.Organization, error) {
	if slug == "" {
		// Simple slug generation
		slug = name // TODO: make URL safe
	}
	org, err := db.CreateOrg(ctx, name, slug)
	if err != nil {
		return nil, err
	}
	err = db.AddMembership(ctx, userID, org.ID, "owner")
	if err != nil {
		return nil, err
	}
	return org, nil
}
