import { and, desc, eq } from "drizzle-orm";
import { db } from "./db";
import { orders } from "@/schema/orders";
import { subscriptions } from "@/schema/subscriptions";

export async function hasProduct(userId: string, productId: string) {
  const order = await db.query.orders.findFirst({
    where: and(eq(orders.userId, userId), eq(orders.productId, productId)),
  });
  if (!order) {
    return false;
  }
  return true;
}

export async function hasActiveSubscription(userId: string) {
  const subscription = await db.query.subscriptions.findFirst({
    where: eq(subscriptions.userId, userId),
    orderBy: desc(subscriptions.createdAt),
  });

  if (!subscription) {
    return false;
  }

  if (!subscription.endDate) {
    throw new Error("end date not found");
  }

  const expireDate = new Date(subscription.endDate);
  expireDate.setDate(expireDate.getDate() + 2);
  const now = new Date();

  if (now < expireDate) {
    return true;
  }

  return false;
}
