-- name: CreateReportRequest :one
INSERT INTO report_requests (
        company_id,
        requested_by,
        type,
        metadata
    )
VALUES ($1, $2, $3, $4)
RETURNING *;
-- name: GetAllReportRequests :many
SELECT *
FROM report_request_detail
WHERE (
        company_id = sqlc.narg('company_id')
        OR sqlc.narg('company_id') IS NULL
    )
    AND (
        type = sqlc.narg('type')
        OR sqlc.narg('type') IS NULL
    )
    AND (
        status = sqlc.narg('status')
        OR sqlc.narg('status') IS NULL
    )
    AND (
        requested_by = sqlc.narg('requested_by')
        OR sqlc.narg('requested_by') IS NULL
    )
ORDER BY id DESC
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: GetTotalReportRequests :one
SELECT COUNT(id)
FROM report_request_detail
WHERE (
        company_id = sqlc.narg('company_id')
        OR sqlc.narg('company_id') IS NULL
    )
    AND (
        type = sqlc.narg('type')
        OR sqlc.narg('type') IS NULL
    )
    AND (
        status = sqlc.narg('status')
        OR sqlc.narg('status') IS NULL
    )
    AND (
        requested_by = sqlc.narg('requested_by')
        OR sqlc.narg('requested_by') IS NULL
    );
-- name: GetReportRequestByID :one
SELECT *
FROM report_request_detail
WHERE id = $1;
-- name: GetReportRequestByRequestedByID :many
SELECT *
FROM report_request_detail
WHERE requested_by = $1
    AND (
        type = sqlc.narg('type')
        OR sqlc.narg('type') IS NULL
    )
    AND (
        status = sqlc.narg('status')
        OR sqlc.narg('status') IS NULL
    )
ORDER BY id DESC
LIMIT sqlc.narg('limit') OFFSET sqlc.narg('offset');
-- name: UpdateReportRequest :exec
UPDATE report_requests
SET file_path = COALESCE(sqlc.narg(file_path), file_path),
    reject_reason = COALESCE(sqlc.narg(reject_reason), reject_reason),
    status = COALESCE(sqlc.narg(status), status),
    completed_at = now()
WHERE id = $1;