-- name: InsertLeague :exec
INSERT INTO leagues (
        id,
        name,
        country_code,
        bet365_id,
        sport_id,
        default_is_active,
        default_is_featured
    )
VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (id) DO
UPDATE
SET name = EXCLUDED.name,
    country_code = EXCLUDED.country_code,
    bet365_id = EXCLUDED.bet365_id,
    sport_id = EXCLUDED.sport_id;
-- name: InsertLeagueSettings :exec
INSERT INTO company_league_settings (
        company_id,
        league_id,
        is_active,
        is_featured
    )
VALUES ($1, $2, $3, $4) ON CONFLICT(company_id, league_id) DO
UPDATE
SET is_active = EXCLUDED.is_active,
    is_featured = EXCLUDED.is_featured;
-- name: GetAllLeagues :many
SELECT *
FROM leagues
WHERE (
        country_code = sqlc.narg('country_code')
        OR sqlc.narg('country_code') IS NULL
    )
    AND (
        sport_id = sqlc.narg('sport_id')
        OR sqlc.narg('sport_id') IS NULL
    )
ORDER BY name ASC
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetAllLeaguesWithSettings :many
SELECT *
FROM league_with_settings
WHERE (company_id = $1)
    AND (
        country_code = sqlc.narg('country_code')
        OR sqlc.narg('country_code') IS NULL
    )
    AND (
        sport_id = sqlc.narg('sport_id')
        OR sqlc.narg('sport_id') IS NULL
    )
    AND (
        is_active = sqlc.narg('is_active')
        OR sqlc.narg('is_active') IS NULL
    )
    AND (
        is_featured = sqlc.narg('is_featured')
        OR sqlc.narg('is_featured') IS NULL
    )
ORDER BY is_featured DESC,
    name ASC
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: CheckLeagueSupport :one
SELECT EXISTS(
        SELECT 1
        FROM company_league_settings
        WHERE league_id = $1
            AND company_id = $2
            AND is_active = true
    );
-- name: UpdateLeague :exec
UPDATE leagues
SET name = COALESCE(sqlc.narg('name'), name),
    country_code = COALESCE(sqlc.narg('country_code'), country_code),
    bet365_id = COALESCE(sqlc.narg('bet365_id'), bet365_id),
    sport_id = COALESCE(sqlc.narg('sport_id'), sport_id)
WHERE id = $1;
-- name: UpdateLeagueSettings :exec
UPDATE company_league_settings
SET is_active = COALESCE(sqlc.narg('is_active'), is_active),
    is_featured = COALESCE(
        sqlc.narg('is_featured'),
        is_featured
    )
WHERE league_id = $1
    AND company_id = $2;