import { db } from '../db/db_index'
import { orders, payments, orderStatus } from '../db/schema'
import { eq } from 'drizzle-orm'

export async function getOrderById(orderId: number) {
  return db.query.orders.findFirst({
    where: eq(orders.id, orderId),
  })
}

export async function getPaymentByOrderId(orderId: number) {
  return db.query.payments.findFirst({
    where: eq(payments.orderId, orderId),
  })
}

export async function getPaymentByMerchantOrderId(merchantOrderId: string) {
  return db.query.payments.findFirst({
    where: eq(payments.merchantOrderId, merchantOrderId),
  })
}

export async function updatePaymentSuccess(merchantOrderId: string, payload: unknown) {
  const [updatedPayment] = await db
    .update(payments)
    .set({
      status: 'success',
      payload,
    })
    .where(eq(payments.merchantOrderId, merchantOrderId))
    .returning({
      id: payments.id,
      orderId: payments.orderId,
    })

  return updatedPayment || null
}

export async function updateOrderPaymentStatus(orderId: number, status: 'pending' | 'success' | 'cod' | 'failed') {
  await db
    .update(orderStatus)
    .set({ paymentStatus: status })
    .where(eq(orderStatus.orderId, orderId))
}

export async function markPaymentFailed(paymentId: number) {
  await db
    .update(payments)
    .set({ status: 'failed' })
    .where(eq(payments.id, paymentId))
}
