package data

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

const (
	RoleViewer             = "viewer"
	RoleContributor        = "contributor"
	RoleAdmin              = "admin"
	RoleMemberOfParliament = "member_of_parliament"
	RolePartyLeadership    = "party_leadership"
)

type Role struct {
	ID   int64
	Code string
}

type RoleModel struct {
	DB *sql.DB
}

func (m RoleModel) AssignToUser(userID int64, roleCode string) error {
	query := `
INSERT INTO users_roles
SELECT $1, id FROM roles WHERE code = $2
ON CONFLICT DO NOTHING`

	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	_, err := m.DB.ExecContext(ctx, query, userID, roleCode)
	return err
}

func (m RoleModel) GetAllForUser(userID int64) ([]Role, error) {
	query := `
SELECT roles.id, roles.code
FROM roles
INNER JOIN users_roles ON users_roles.role_id = roles.id
WHERE users_roles.user_id = $1`

	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	rows, err := m.DB.QueryContext(ctx, query, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var roles []Role
	for rows.Next() {
		var role Role
		if err := rows.Scan(&role.ID, &role.Code); err != nil {
			return nil, err
		}
		roles = append(roles, role)
	}
	return roles, rows.Err()
}
