-- =====================
-- Payments
-- =====================

-- name: CreatePayment :one
INSERT INTO payments (
    user_id, plan_id, subscription_id, session_id, transaction_id, nonce,
    amount, currency, payment_method, status, payment_url, expires_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, COALESCE($10, 'PENDING'), $11, $12)
RETURNING *;

-- name: GetPaymentByID :one
SELECT * FROM payments WHERE id = $1;

-- name: GetPaymentBySessionID :one
SELECT * FROM payments WHERE session_id = $1;

-- name: GetPaymentByNonce :one
SELECT * FROM payments WHERE nonce = $1;

-- name: GetPaymentByTransactionID :one
SELECT * FROM payments WHERE transaction_id = $1;

-- name: GetPaymentsByUserID :many
SELECT p.*, sp.name AS plan_name
FROM payments p
LEFT JOIN subscription_plans sp ON sp.id = p.plan_id
WHERE p.user_id = $1
ORDER BY p.created_at DESC
LIMIT sqlc.narg('limit')::INT
OFFSET sqlc.narg('offset')::INT;

-- name: GetPendingPaymentsByUserID :many
SELECT * FROM payments
WHERE user_id = $1 AND status = 'PENDING'
ORDER BY created_at DESC;

-- name: UpdatePaymentStatus :exec
UPDATE payments
SET 
    status = $1,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $2;

-- name: UpdatePaymentStatusBySessionID :exec
UPDATE payments
SET 
    status = $1,
    transaction_id = COALESCE($2, transaction_id),
    payment_method = COALESCE($3, payment_method),
    paid_at = CASE WHEN $1 = 'SUCCESS' THEN CURRENT_TIMESTAMP ELSE paid_at END,
    updated_at = CURRENT_TIMESTAMP
WHERE session_id = $4;

-- name: UpdatePaymentStatusByNonce :exec
UPDATE payments
SET 
    status = $1,
    transaction_id = COALESCE($2, transaction_id),
    payment_method = COALESCE($3, payment_method),
    paid_at = CASE WHEN $1 = 'SUCCESS' THEN CURRENT_TIMESTAMP ELSE paid_at END,
    updated_at = CURRENT_TIMESTAMP
WHERE nonce = $4;

-- name: UpdatePaymentSessionID :exec
UPDATE payments
SET 
    session_id = $1,
    payment_url = $2,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $3;

-- name: LinkPaymentToSubscription :exec
UPDATE payments
SET 
    subscription_id = $1,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $2;

-- name: GetExpiredPendingPayments :many
SELECT * FROM payments
WHERE status = 'PENDING'
  AND expires_at IS NOT NULL
  AND expires_at <= CURRENT_TIMESTAMP;

-- name: ExpirePayment :exec
UPDATE payments
SET 
    status = 'EXPIRED',
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1;

-- name: CountUserPayments :one
SELECT COUNT(*) FROM payments WHERE user_id = $1;
