package migration

import "strings"

// googleWorkspaceExport maps Google native mime types to export targets.
func googleWorkspaceExport(mimeType string) (exportMime, ext string, ok bool) {
	switch mimeType {
	case "application/vnd.google-apps.document":
		return "application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx", true
	case "application/vnd.google-apps.spreadsheet":
		return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx", true
	case "application/vnd.google-apps.presentation":
		return "application/vnd.openxmlformats-officedocument.presentationml.presentation", ".pptx", true
	case "application/vnd.google-apps.drawing":
		return "application/pdf", ".pdf", true
	case "application/vnd.google-apps.script":
		return "application/vnd.google-apps.script+json", ".json", true
	case "application/vnd.google-apps.site":
		return "text/plain", ".txt", true
	default:
		return "", "", false
	}
}

// googleSlidesPDFExport returns PDF export for Google Slides (companion copy).
func googleSlidesPDFExport(mimeType string) (exportMime, ext string, ok bool) {
	if mimeType == "application/vnd.google-apps.presentation" {
		return "application/pdf", ".pdf", true
	}
	return "", "", false
}

func driveExportFileName(name, ext string) string {
	name = strings.TrimSpace(name)
	if name == "" {
		name = "untitled"
	}
	if ext != "" && !strings.HasSuffix(strings.ToLower(name), strings.ToLower(ext)) {
		return name + ext
	}
	return name
}

type driveFolderRef struct {
	ID      string
	Path    string
	DriveID string // Google shared drive ID; empty for My Drive
	Shared  bool
}

func readDriveFolderQueue(cursor map[string]any, provider string) []driveFolderRef {
	raw, _ := cursor["folderQueue"].([]any)
	out := make([]driveFolderRef, 0, len(raw))
	for _, item := range raw {
		m, _ := item.(map[string]any)
		if m == nil {
			continue
		}
		id, _ := m["id"].(string)
		p, _ := m["path"].(string)
		driveID, _ := m["driveId"].(string)
		shared, _ := m["shared"].(bool)
		if id != "" {
			out = append(out, driveFolderRef{ID: id, Path: p, DriveID: driveID, Shared: shared})
		}
	}
	if len(out) == 0 {
		if provider == "google" {
			return []driveFolderRef{{ID: "root", Path: ""}}
		}
		return []driveFolderRef{{ID: "root", Path: ""}}
	}
	return out
}

func writeDriveFolderQueue(cursor map[string]any, queue []driveFolderRef) {
	raw := make([]any, 0, len(queue))
	for _, f := range queue {
		raw = append(raw, map[string]any{
			"id": f.ID, "path": f.Path, "driveId": f.DriveID, "shared": f.Shared,
		})
	}
	cursor["folderQueue"] = raw
}

func enqueueDriveFolder(queue []driveFolderRef, folder driveFolderRef) []driveFolderRef {
	for _, existing := range queue {
		if existing.ID == folder.ID && existing.DriveID == folder.DriveID {
			return queue
		}
	}
	return append(queue, folder)
}
