import { prisma as db } from "@repo/db/client";
import { InsertNpiProvider, NpiProvider } from "@repo/db/types";

export interface INpiProviderStorage {
  getNpiProvider(id: number): Promise<NpiProvider | null>;
  getNpiProvidersByUser(userId: number): Promise<NpiProvider[]>;
  createNpiProvider(data: InsertNpiProvider): Promise<NpiProvider>;
  updateNpiProvider(
    id: number,
    updates: Partial<NpiProvider>,
  ): Promise<NpiProvider | null>;
  deleteNpiProvider(userId: number, id: number): Promise<boolean>;
  reorderNpiProviders(userId: number, orderedIds: number[]): Promise<void>;
}

export const npiProviderStorage: INpiProviderStorage = {
  async getNpiProvider(id: number) {
    return db.npiProvider.findUnique({ where: { id } });
  },

  async getNpiProvidersByUser(userId: number) {
    return db.npiProvider.findMany({
      where: { userId },
      orderBy: [{ sortOrder: "asc" }, { id: "asc" }],
    });
  },

  async createNpiProvider(data: InsertNpiProvider) {
    return db.npiProvider.create({
      data: data as NpiProvider,
    });
  },

  async updateNpiProvider(id: number, updates: Partial<NpiProvider>) {
    return db.npiProvider.update({
      where: { id },
      data: updates,
    });
  },

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

  async reorderNpiProviders(userId: number, orderedIds: number[]) {
    await Promise.all(
      orderedIds.map((id, index) =>
        db.npiProvider.update({
          where: { id, userId },
          data: { sortOrder: index + 1 },
        })
      )
    );
  },
};
