import { config } from "dotenv";

config({ path: ".env.local" });
config();

async function upsertSeed() {
  const [{ eq }, { db, queryClient }, schema, { siteConfig }] =
    await Promise.all([
      import("drizzle-orm"),
      import("@/db/client"),
      import("@/db/schema"),
      import("@/config/site"),
    ]);

  const {
    accommodationTypes,
    amenities,
    applicationSettings,
    properties,
    propertyAmenities,
    ratePlans,
    roles,
    units,
  } = schema;

  const [existingProperty] = await db
    .select()
    .from(properties)
    .where(eq(properties.slug, "alya-paros"))
    .limit(1);

  const [property] = existingProperty
    ? [existingProperty]
    : await db
        .insert(properties)
        .values({
          slug: "alya-paros",
          name: siteConfig.name,
          registrationNumber: siteConfig.registrationNumber,
          timezone: siteConfig.timezone,
          currency: siteConfig.currency,
          sourceUrl: siteConfig.sourceUrl,
        })
        .returning();

  const [accommodation] = await db
    .insert(accommodationTypes)
    .values({
      propertyId: property.id,
      slug: "calm-cycladic-home",
      name: "Calm Cycladic Home",
      maxGuests: siteConfig.maxGuests,
      bedrooms: siteConfig.bedrooms,
      beds: siteConfig.beds,
      baths: siteConfig.baths,
    })
    .onConflictDoNothing()
    .returning();

  const accommodationId =
    accommodation?.id ??
    (
      await db
        .select()
        .from(accommodationTypes)
        .where(eq(accommodationTypes.slug, "calm-cycladic-home"))
        .limit(1)
    )[0].id;

  const [unit] = await db
    .insert(units)
    .values({
      propertyId: property.id,
      accommodationTypeId: accommodationId,
      slug: "alya-paros-main-unit",
      name: "Alya Paros",
    })
    .onConflictDoNothing()
    .returning();

  const unitId =
    unit?.id ??
    (
      await db
        .select()
        .from(units)
        .where(eq(units.slug, "alya-paros-main-unit"))
        .limit(1)
    )[0].id;

  const amenitySeeds = [
    ["courtyard_view", { en: "Courtyard view", el: "Θέα στην αυλή" }],
    ["beach_access", { en: "Beach access", el: "Πρόσβαση στην παραλία" }],
    ["kitchen", { en: "Kitchen", el: "Κουζίνα" }],
    ["wifi", { en: "Wi-Fi", el: "Wi-Fi" }],
    ["workspace", { en: "Dedicated workspace", el: "Χώρος εργασίας" }],
  ] as const;

  for (const [code, label] of amenitySeeds) {
    const [amenity] = await db
      .insert(amenities)
      .values({ code, label })
      .onConflictDoNothing()
      .returning();

    const amenityId =
      amenity?.id ??
      (
        await db.select().from(amenities).where(eq(amenities.code, code)).limit(1)
      )[0].id;

    await db
      .insert(propertyAmenities)
      .values({ propertyId: property.id, amenityId })
      .onConflictDoNothing();
  }

  await db.insert(ratePlans).values({
    unitId,
    name: "Owner review required",
    nightlyMinor: 0,
    currency: siteConfig.currency,
    active: false,
  });

  await db
    .insert(roles)
    .values({
      code: "admin",
      name: "Administrator",
      description: "Full administration access",
    })
    .onConflictDoNothing();

  await db
    .insert(applicationSettings)
    .values({
      key: "booking.mode",
      value: { mode: "request_approval" },
    })
    .onConflictDoUpdate({
      target: applicationSettings.key,
      set: { value: { mode: "request_approval" } },
    });
  await queryClient.end();
}

upsertSeed().catch((error) => {
  console.error(error);
  process.exit(1);
});
