package sqlite

import (
	"context"
	"time"

	"github.com/google/uuid"

	"switchboard-core/database"
	"switchboard-core/models"
)

type ExtensionPermissionStore struct{}

func NewExtensionPermissionStore() *ExtensionPermissionStore {
	return &ExtensionPermissionStore{}
}

func (s *ExtensionPermissionStore) DeclareForPackage(ctx context.Context, packageID string, permissions []string) error {
	tx, err := DB.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	if len(permissions) == 0 {
		_, err = tx.ExecContext(ctx, `DELETE FROM extension_permissions WHERE package_id = ?`, packageID)
		if err != nil {
			return err
		}
		return tx.Commit()
	}

	declared := make(map[string]bool, len(permissions))
	for _, p := range permissions {
		declared[p] = true
	}

	rows, err := tx.QueryContext(ctx,
		`SELECT permission FROM extension_permissions WHERE package_id = ?`, packageID)
	if err != nil {
		return err
	}
	existing := make(map[string]bool)
	for rows.Next() {
		var perm string
		if err := rows.Scan(&perm); err != nil {
			rows.Close()
			return err
		}
		existing[perm] = true
	}
	rows.Close()

	for perm := range existing {
		if !declared[perm] {
			_, err = tx.ExecContext(ctx,
				`DELETE FROM extension_permissions WHERE package_id = ? AND permission = ?`,
				packageID, perm)
			if err != nil {
				return err
			}
		}
	}

	for _, perm := range permissions {
		if !existing[perm] {
			_, err = tx.ExecContext(ctx,
				`INSERT OR IGNORE INTO extension_permissions (id, package_id, permission)
				 VALUES (?, ?, ?)`,
				uuid.New().String(), packageID, perm)
			if err != nil {
				return err
			}
		}
	}

	return tx.Commit()
}

func (s *ExtensionPermissionStore) ListForPackage(ctx context.Context, packageID string) ([]models.ExtensionPermission, error) {
	rows, err := DB.QueryContext(ctx,
		`SELECT id, package_id, permission, granted, granted_by, granted_at, created_at
		 FROM extension_permissions
		 WHERE package_id = ?
		 ORDER BY permission`, packageID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var perms []models.ExtensionPermission
	for rows.Next() {
		var p models.ExtensionPermission
		if err := rows.Scan(&p.ID, &p.PackageID, &p.Permission, &p.Granted,
			&p.GrantedBy, database.SNT(&p.GrantedAt), database.ST(&p.CreatedAt)); err != nil {
			return nil, err
		}
		perms = append(perms, p)
	}
	if perms == nil {
		perms = []models.ExtensionPermission{}
	}
	return perms, nil
}

func (s *ExtensionPermissionStore) GrantedForPackage(ctx context.Context, packageID string) ([]string, error) {
	rows, err := DB.QueryContext(ctx,
		`SELECT permission FROM extension_permissions
		 WHERE package_id = ? AND granted = 1
		 ORDER BY permission`, packageID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var perms []string
	for rows.Next() {
		var p string
		if err := rows.Scan(&p); err != nil {
			return nil, err
		}
		perms = append(perms, p)
	}
	if perms == nil {
		perms = []string{}
	}
	return perms, nil
}

func (s *ExtensionPermissionStore) Grant(ctx context.Context, packageID, permission, grantedBy string) error {
	now := time.Now().UTC().Format(time.RFC3339)
	_, err := DB.ExecContext(ctx,
		`UPDATE extension_permissions
		 SET granted = 1, granted_by = ?, granted_at = ?
		 WHERE package_id = ? AND permission = ?`,
		grantedBy, now, packageID, permission)
	return err
}

func (s *ExtensionPermissionStore) Revoke(ctx context.Context, packageID, permission string) error {
	_, err := DB.ExecContext(ctx,
		`UPDATE extension_permissions
		 SET granted = 0, granted_by = NULL, granted_at = NULL
		 WHERE package_id = ? AND permission = ?`,
		packageID, permission)
	return err
}

func (s *ExtensionPermissionStore) GrantAll(ctx context.Context, packageID, grantedBy string) error {
	now := time.Now().UTC().Format(time.RFC3339)
	_, err := DB.ExecContext(ctx,
		`UPDATE extension_permissions
		 SET granted = 1, granted_by = ?, granted_at = ?
		 WHERE package_id = ? AND granted = 0`,
		grantedBy, now, packageID)
	return err
}

func (s *ExtensionPermissionStore) DeleteForPackage(ctx context.Context, packageID string) error {
	_, err := DB.ExecContext(ctx,
		`DELETE FROM extension_permissions WHERE package_id = ?`, packageID)
	return err
}
