package appregistry

import (
	"context"
	"database/sql"
	"fmt"
)

type Service struct {
	userDB *sql.DB
}

type App struct {
	AppID       int64  `json:"appId"`
	AppCode     string `json:"appCode"`
	AppName     string `json:"appName"`
	LogoURL     string `json:"logoUrl"`
	PackageName string `json:"packageName"`
	Platform    string `json:"platform"`
	Status      string `json:"status"`
	CreatedAtMs int64  `json:"createdAtMs"`
	UpdatedAtMs int64  `json:"updatedAtMs"`
}

func NewService(userDB *sql.DB) *Service {
	return &Service{userDB: userDB}
}

func (s *Service) ListApps(ctx context.Context) ([]App, error) {
	if s.userDB == nil {
		return nil, fmt.Errorf("user mysql is not configured")
	}
	rows, err := s.userDB.QueryContext(ctx, `
		SELECT app_id, app_code, app_name, logo_url, package_name, platform, status, created_at_ms, updated_at_ms
		FROM apps
		WHERE status = 'active'
		ORDER BY app_name ASC, app_code ASC
	`)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	items := []App{}
	for rows.Next() {
		var item App
		if err := rows.Scan(&item.AppID, &item.AppCode, &item.AppName, &item.LogoURL, &item.PackageName, &item.Platform, &item.Status, &item.CreatedAtMs, &item.UpdatedAtMs); err != nil {
			return nil, err
		}
		items = append(items, item)
	}
	return items, rows.Err()
}
