-- name: InsertNonLiveOdd :exec
INSERT INTO odds (
    event_id,
    fi,
    market_type,
    market_name,
    market_category,
    market_id,
    name,
    handicap,
    odds_value,
    section,
    category,
    raw_odds,
    is_active,
    source,
    fetched_at
) VALUES (
    $1, $2, $3, $4, $5, $6, $7,
    $8, $9, $10, $11, $12, $13, $14, $15
)
ON CONFLICT (event_id, market_id) DO UPDATE SET
    odds_value      = EXCLUDED.odds_value,
    raw_odds        = EXCLUDED.raw_odds,
    market_type     = EXCLUDED.market_type,
    market_name     = EXCLUDED.market_name,
    market_category = EXCLUDED.market_category,
    name            = EXCLUDED.name,
    handicap        = EXCLUDED.handicap,
    fetched_at      = EXCLUDED.fetched_at,
    is_active       = EXCLUDED.is_active,
    source          = EXCLUDED.source,
    fi              = EXCLUDED.fi;




-- name: GetPrematchOdds :many
SELECT 
    event_id,
    fi,
    market_type,
    market_name,
    market_category,
    market_id,
    name,
    handicap,
    odds_value,
    section,
    category,
    raw_odds,
    fetched_at,
    source,
    is_active
FROM odds
WHERE is_active = true AND source = 'b365api';

-- name: GetALLPrematchOdds :many
SELECT 
    event_id,
    fi,
    market_type,
    market_name,
    market_category,
    market_id,
    name,
    handicap,
    odds_value,
    section,
    category,
    raw_odds,
    fetched_at,
    source,
    is_active
FROM odds
WHERE is_active = true AND source = 'b365api';

-- name: GetRawOddsByID :one
SELECT 
    id, 
    raw_odds, 
    fetched_at
FROM odds
WHERE 
    raw_odds @> $1::jsonb AND 
    is_active = true AND 
    source = 'b365api'
LIMIT 1;

-- name: GetPrematchOddsByUpcomingID :many
SELECT 
    o.event_id,
    o.fi,
    o.market_type,
    o.market_name,
    o.market_category,
    o.market_id,
    o.name,
    o.handicap,
    o.odds_value,
    o.section,
    o.category,
    o.raw_odds,
    o.fetched_at,
    o.source,
    o.is_active
FROM odds o
JOIN events e ON o.fi = e.id
WHERE e.id = $1
  AND e.is_live = false
  AND e.status = 'upcoming'
  AND o.is_active = true
  AND o.source = 'b365api'
LIMIT $2 OFFSET $3;