import { InsertShoppingVendor, ShoppingVendor } from "@repo/db/types";
import { prisma as db } from "@repo/db/client";

export interface IShoppingVendorStorage {
  getShoppingVendor(id: number): Promise<ShoppingVendor | null>;
  getShoppingVendorsByUser(userId: number): Promise<ShoppingVendor[]>;
  createShoppingVendor(data: InsertShoppingVendor): Promise<ShoppingVendor>;
  updateShoppingVendor(id: number, updates: Partial<ShoppingVendor>): Promise<ShoppingVendor | null>;
  deleteShoppingVendor(userId: number, id: number): Promise<boolean>;
}

export const shoppingVendorStorage: IShoppingVendorStorage = {
  async getShoppingVendor(id: number) {
    return await db.shoppingVendor.findUnique({ where: { id } }) as ShoppingVendor | null;
  },

  async getShoppingVendorsByUser(userId: number) {
    return await db.shoppingVendor.findMany({ where: { userId }, orderBy: { id: "asc" } }) as ShoppingVendor[];
  },

  async createShoppingVendor(data: InsertShoppingVendor) {
    return await db.shoppingVendor.create({ data }) as ShoppingVendor;
  },

  async updateShoppingVendor(id: number, updates: Partial<ShoppingVendor>) {
    return await db.shoppingVendor.update({ where: { id }, data: updates }) as ShoppingVendor;
  },

  async deleteShoppingVendor(userId: number, id: number) {
    try {
      await db.shoppingVendor.delete({ where: { userId, id } });
      return true;
    } catch {
      return false;
    }
  },
};
