-- name: CreateUser :one
INSERT INTO users (username, password_hash)
VALUES ($1, $2)
RETURNING *;

-- name: GetUserByUsername :one
SELECT * FROM users WHERE username = $1;

-- name: ResetLoginFailures :exec
UPDATE users
SET failed_login_attempts = 0,
    locked_until = NULL
WHERE username = $1;

-- name: RecordFailedLogin :one
UPDATE users
SET failed_login_attempts = CASE
        WHEN failed_login_attempts + 1 >= 3 THEN 3
        ELSE failed_login_attempts + 1
    END,
    locked_until = CASE
        WHEN failed_login_attempts + 1 >= 3 THEN NOW() + INTERVAL '5 minutes'
        ELSE locked_until
    END
WHERE username = $1
RETURNING failed_login_attempts, locked_until;

-- name: GetDeliveriesByDate :many
SELECT * FROM deliveries WHERE date = $1;
 
-- name: CreateDelivery :one
INSERT INTO deliveries (
    date, pickup_location, pickup_location_2, warehouse_request_source, warehouse_request_source_2, product_name, product_name_2,
    customer_name, address, street, house, apartment, entrance, floor,
    phone, additional_phone, has_elevator, payment_status, service_info, comment
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20)
RETURNING *;

-- name: GetDeliveryByID :one
SELECT * FROM deliveries WHERE id = $1;

-- name: DeleteDelivery :exec
DELETE FROM deliveries WHERE id = $1;

-- name: UpdateDelivery :exec
UPDATE deliveries SET
    date = $1,
    pickup_location = $2,
    pickup_location_2 = $3,
    warehouse_request_source = $4,
    warehouse_request_source_2 = $5,
    product_name = $6,
    product_name_2 = $7,
    customer_name = $8,
    address = $9,
    street = $10,
    house = $11,
    apartment = $12,
    entrance = $13,
    floor = $14,
    phone = $15,
    additional_phone = $16,
    has_elevator = $17,
    payment_status = $18,
    service_info = $19,
    comment = $20,
    updated_at = NOW()
WHERE id = $21;

-- name: GetDeliveryCount :many
SELECT COUNT(*) as count, date FROM deliveries
WHERE date >= CURRENT_DATE
  AND date < GREATEST(
    CURRENT_DATE + INTERVAL '7 days',
    DATE_TRUNC('month', CURRENT_DATE) + INTERVAL '1 month'
  )
GROUP BY date;

-- name: UpdateDeliveryStatus :exec
UPDATE deliveries SET status = $1, updated_at = NOW() WHERE id = $2;
