import { db } from '../db/db_index';
import { storeInfo, productInfo } from '../db/schema';
import { eq, inArray } from 'drizzle-orm';

export interface Store {
  id: number;
  name: string;
  description: string | null;
  imageUrl: string | null;
  owner: number;
  createdAt: Date;
  // updatedAt: Date;
}

export async function getAllStores(): Promise<any[]> {
  const stores = await db.query.storeInfo.findMany({
    with: {
      owner: true,
    },
  });

  return stores;
}

export async function getStoreById(id: number): Promise<any | null> {
  const store = await db.query.storeInfo.findFirst({
    where: eq(storeInfo.id, id),
    with: {
      owner: true,
    },
  });

  return store || null;
}

export interface CreateStoreInput {
  name: string;
  description?: string;
  imageUrl?: string;
  owner: number;
}

export async function createStore(
  input: CreateStoreInput,
  products?: number[]
): Promise<Store> {
  const [newStore] = await db
    .insert(storeInfo)
    .values({
      name: input.name,
      description: input.description,
      imageUrl: input.imageUrl,
      owner: input.owner,
    })
    .returning();

  if (products && products.length > 0) {
    await db
      .update(productInfo)
      .set({ storeId: newStore.id })
      .where(inArray(productInfo.id, products));
  }

  return {
    id: newStore.id,
    name: newStore.name,
    description: newStore.description,
    imageUrl: newStore.imageUrl,
    owner: newStore.owner,
    createdAt: newStore.createdAt,
    // updatedAt: newStore.updatedAt,
  };
}

export interface UpdateStoreInput {
  name?: string;
  description?: string;
  imageUrl?: string;
  owner?: number;
}

export async function updateStore(
  id: number,
  input: UpdateStoreInput,
  products?: number[]
): Promise<Store> {
  const [updatedStore] = await db
    .update(storeInfo)
    .set({
      ...input,
      // updatedAt: new Date(),
    })
    .where(eq(storeInfo.id, id))
    .returning();

  if (!updatedStore) {
    throw new Error("Store not found");
  }

  if (products !== undefined) {
    await db
      .update(productInfo)
      .set({ storeId: null })
      .where(eq(productInfo.storeId, id));

    if (products.length > 0) {
      await db
        .update(productInfo)
        .set({ storeId: id })
        .where(inArray(productInfo.id, products));
    }
  }

  return {
    id: updatedStore.id,
    name: updatedStore.name,
    description: updatedStore.description,
    imageUrl: updatedStore.imageUrl,
    owner: updatedStore.owner,
    createdAt: updatedStore.createdAt,
    // updatedAt: updatedStore.updatedAt,
  };
}

export async function deleteStore(id: number): Promise<{ message: string }> {
  return await db.transaction(async (tx) => {
    await tx
      .update(productInfo)
      .set({ storeId: null })
      .where(eq(productInfo.storeId, id));

    const [deletedStore] = await tx
      .delete(storeInfo)
      .where(eq(storeInfo.id, id))
      .returning();

    if (!deletedStore) {
      throw new Error("Store not found");
    }

    return {
      message: "Store deleted successfully",
    };
  });
}
