'use strict';

const bcrypt = require('bcrypt');
const config = require('../../config');
const db = require('../models');

const IDS = {
  users: {
    buyerAdmin: '70000000-0000-4000-8000-000000000001',
    buyer: '70000000-0000-4000-8000-000000000002',
    salesRep: '70000000-0000-4000-8000-000000000003',
  },
  accounts: {
    harbor: '71000000-0000-4000-8000-000000000001',
    cedar: '71000000-0000-4000-8000-000000000002',
    seabrook: '71000000-0000-4000-8000-000000000003',
  },
  locations: {
    harborDowntown: '72000000-0000-4000-8000-000000000001',
    harborRiverNorth: '72000000-0000-4000-8000-000000000002',
    cedarKitchen: '72000000-0000-4000-8000-000000000003',
    seabrookMidtown: '72000000-0000-4000-8000-000000000004',
    seabrookWaterfront: '72000000-0000-4000-8000-000000000005',
  },
  contacts: {
    maria: '73000000-0000-4000-8000-000000000001',
    owen: '73000000-0000-4000-8000-000000000002',
    dana: '73000000-0000-4000-8000-000000000003',
    priya: '73000000-0000-4000-8000-000000000004',
    luca: '73000000-0000-4000-8000-000000000005',
  },
  categories: {
    dairy: '74000000-0000-4000-8000-000000000001',
    pantry: '74000000-0000-4000-8000-000000000002',
    proteins: '74000000-0000-4000-8000-000000000003',
    frozen: '74000000-0000-4000-8000-000000000004',
  },
  products: {
    burrata: '75000000-0000-4000-8000-000000000001',
    ricottaSalata: '75000000-0000-4000-8000-000000000002',
    chiliCrunch: '75000000-0000-4000-8000-000000000003',
    demiGlace: '75000000-0000-4000-8000-000000000004',
    duckConfit: '75000000-0000-4000-8000-000000000005',
    bloodOrangeSorbet: '75000000-0000-4000-8000-000000000006',
    fetaCrumble: '75000000-0000-4000-8000-000000000007',
  },
  priceLists: {
    harbor: '76000000-0000-4000-8000-000000000001',
    cedar: '76000000-0000-4000-8000-000000000002',
    seabrook: '76000000-0000-4000-8000-000000000003',
  },
  accountPriceLists: {
    harbor: '77000000-0000-4000-8000-000000000001',
    cedar: '77000000-0000-4000-8000-000000000002',
    seabrook: '77000000-0000-4000-8000-000000000003',
  },
  priceListItems: {
    harborBurrata: '78000000-0000-4000-8000-000000000001',
    harborRicotta: '78000000-0000-4000-8000-000000000002',
    harborChili: '78000000-0000-4000-8000-000000000003',
    harborDemi: '78000000-0000-4000-8000-000000000004',
    harborDuck: '78000000-0000-4000-8000-000000000005',
    harborSorbet: '78000000-0000-4000-8000-000000000006',
    harborFeta: '78000000-0000-4000-8000-000000000007',
    cedarBurrata: '78000000-0000-4000-8000-000000000008',
    cedarRicotta: '78000000-0000-4000-8000-000000000009',
    cedarChili: '78000000-0000-4000-8000-000000000010',
    cedarDemi: '78000000-0000-4000-8000-000000000011',
    cedarDuck: '78000000-0000-4000-8000-000000000012',
    cedarSorbet: '78000000-0000-4000-8000-000000000013',
    cedarFeta: '78000000-0000-4000-8000-000000000014',
    seabrookBurrata: '78000000-0000-4000-8000-000000000015',
    seabrookRicotta: '78000000-0000-4000-8000-000000000016',
    seabrookChili: '78000000-0000-4000-8000-000000000017',
    seabrookDemi: '78000000-0000-4000-8000-000000000018',
    seabrookDuck: '78000000-0000-4000-8000-000000000019',
    seabrookSorbet: '78000000-0000-4000-8000-000000000020',
    seabrookFeta: '78000000-0000-4000-8000-000000000021',
  },
  quotes: {
    harbor: '79000000-0000-4000-8000-000000000001',
    cedar: '79000000-0000-4000-8000-000000000002',
    seabrook: '79000000-0000-4000-8000-000000000003',
  },
  quoteItems: {
    harborBurrata: '79100000-0000-4000-8000-000000000001',
    harborChili: '79100000-0000-4000-8000-000000000002',
    cedarSorbet: '79100000-0000-4000-8000-000000000003',
    seabrookDuck: '79100000-0000-4000-8000-000000000004',
    seabrookDemi: '79100000-0000-4000-8000-000000000005',
  },
  sampleRequests: {
    harbor: '79200000-0000-4000-8000-000000000001',
    cedar: '79200000-0000-4000-8000-000000000002',
    seabrook: '79200000-0000-4000-8000-000000000003',
  },
  savedLists: {
    harborWeekend: '79210000-0000-4000-8000-000000000001',
    harborChefCounter: '79210000-0000-4000-8000-000000000002',
    seabrookBanquet: '79210000-0000-4000-8000-000000000003',
  },
  savedListItems: {
    harborWeekendBurrata: '79220000-0000-4000-8000-000000000001',
    harborWeekendChili: '79220000-0000-4000-8000-000000000002',
    harborWeekendFeta: '79220000-0000-4000-8000-000000000003',
    harborChefCounterDuck: '79220000-0000-4000-8000-000000000004',
    harborChefCounterSorbet: '79220000-0000-4000-8000-000000000005',
    seabrookBanquetDemi: '79220000-0000-4000-8000-000000000006',
    seabrookBanquetBurrata: '79220000-0000-4000-8000-000000000007',
  },
  orders: {
    harborDelivered: '79300000-0000-4000-8000-000000000001',
    harborSubmitted: '79300000-0000-4000-8000-000000000002',
    seabrookDelivered: '79300000-0000-4000-8000-000000000003',
  },
  orderItems: {
    harborDeliveredBurrata: '79400000-0000-4000-8000-000000000001',
    harborDeliveredChili: '79400000-0000-4000-8000-000000000002',
    harborDeliveredFeta: '79400000-0000-4000-8000-000000000003',
    harborSubmittedDuck: '79400000-0000-4000-8000-000000000004',
    harborSubmittedSorbet: '79400000-0000-4000-8000-000000000005',
    seabrookDeliveredDemi: '79400000-0000-4000-8000-000000000006',
    seabrookDeliveredBurrata: '79400000-0000-4000-8000-000000000007',
  },
};

function daysFromNow(offset, hour = 14) {
  const date = new Date();
  date.setUTCHours(hour, 0, 0, 0);
  date.setUTCDate(date.getUTCDate() + offset);
  return date;
}

async function upsertRecord(model, id, values, transaction) {
  const existing = await model.findByPk(id, { transaction, paranoid: false });

  if (existing) {
    try {
      await existing.update(values, { transaction });
      return existing;
    } catch (error) {
      console.error(
        'Demo seed update failed:',
        model.name,
        id,
        error.parent?.detail || error.parent?.message || error.message,
        values,
      );
      throw error;
    }
  }

  try {
    return await model.create({ id, ...values }, { transaction });
  } catch (error) {
    console.error(
      'Demo seed create failed:',
      model.name,
      id,
      error.parent?.detail || error.parent?.message || error.message,
      values,
    );
    throw error;
  }
}

async function grantPermission(roleName, permissionName, transaction) {
  const role = await db.roles.findOne({
    where: {
      name: roleName,
    },
    transaction,
  });
  const permission = await db.permissions.findOne({
    where: {
      name: permissionName,
    },
    transaction,
  });

  if (!role || !permission) {
    throw new Error(
      `Missing role or permission: ${roleName} / ${permissionName}`,
    );
  }

  await db.sequelize.query(
    `
      INSERT INTO "rolesPermissionsPermissions"
        ("createdAt", "updatedAt", "roles_permissionsId", "permissionId")
      VALUES
        (:createdAt, :updatedAt, :roleId, :permissionId)
      ON CONFLICT ("roles_permissionsId", "permissionId") DO NOTHING
    `,
    {
      replacements: {
        createdAt: new Date(),
        updatedAt: new Date(),
        roleId: role.id,
        permissionId: permission.id,
      },
      transaction,
    },
  );
}

module.exports = {
  async up() {
    const passwordHash = bcrypt.hashSync(
      config.user_pass,
      config.bcrypt.saltRounds,
    );

    await db.sequelize.transaction(async (transaction) => {
      await grantPermission(
        'Customer Buyer Admin',
        'CREATE_ORDERS',
        transaction,
      );
      await grantPermission(
        'Customer Buyer Admin',
        'CREATE_ORDER_ITEMS',
        transaction,
      );
      await grantPermission('Customer Buyer', 'CREATE_ORDERS', transaction);
      await grantPermission(
        'Customer Buyer',
        'CREATE_ORDER_ITEMS',
        transaction,
      );

      const adminUser = await db.users.findOne({
        where: {
          email: config.admin_email,
        },
        transaction,
      });

      const buyerAdminRole = await db.roles.findOne({
        where: {
          name: 'Customer Buyer Admin',
        },
        transaction,
      });
      const buyerRole = await db.roles.findOne({
        where: {
          name: 'Customer Buyer',
        },
        transaction,
      });
      const salesRepRole = await db.roles.findOne({
        where: {
          name: 'Sales Representative',
        },
        transaction,
      });

      if (!adminUser || !buyerAdminRole || !buyerRole || !salesRepRole) {
        throw new Error('Required seed references were not found.');
      }

      await upsertRecord(
        db.users,
        IDS.users.salesRep,
        {
          firstName: 'Nina',
          lastName: 'Shah',
          phoneNumber: '312-555-0188',
          email: 'nina.shah@northstar-specialty.com',
          disabled: false,
          password: passwordHash,
          emailVerified: true,
          provider: config.providers.LOCAL,
          app_roleId: salesRepRole.id,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.users,
        IDS.users.buyerAdmin,
        {
          firstName: 'Maria',
          lastName: 'Alvarez',
          phoneNumber: '312-555-0141',
          email: 'maria.alvarez@harbortable.com',
          disabled: false,
          password: passwordHash,
          emailVerified: true,
          provider: config.providers.LOCAL,
          app_roleId: buyerAdminRole.id,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.users,
        IDS.users.buyer,
        {
          firstName: 'Owen',
          lastName: 'Price',
          phoneNumber: '312-555-0170',
          email: 'owen.price@harbortable.com',
          disabled: false,
          password: passwordHash,
          emailVerified: true,
          provider: config.providers.LOCAL,
          app_roleId: buyerRole.id,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.product_categories,
        IDS.categories.dairy,
        {
          category_name: 'Cultured Dairy & Cheese',
          category_description:
            'Imported cheeses, cultured dairy, and finishing ingredients for menu differentiation.',
          is_active: true,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.product_categories,
        IDS.categories.pantry,
        {
          category_name: 'Chef Pantry Essentials',
          category_description:
            'High-flavor pantry shortcuts for finishing, sauce work, and premium mise en place.',
          is_active: true,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.product_categories,
        IDS.categories.proteins,
        {
          category_name: 'Prepared Proteins',
          category_description:
            'Labor-saving proteins sized for banquets, tasting menus, and high-volume service.',
          is_active: true,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.product_categories,
        IDS.categories.frozen,
        {
          category_name: 'Frozen Desserts',
          category_description:
            'Premium frozen desserts ready for plated desserts, bars, and banqueting programs.',
          is_active: true,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.products,
        IDS.products.burrata,
        {
          sku: 'NS-BUR-2X1K',
          product_name: 'Burrata di Puglia',
          brand: 'Northstar Reserve',
          short_description:
            'Hand-pulled burrata with a creamy stracciatella center for share plates and pizza finishing.',
          long_description:
            'Creamy Italian burrata packed in foodservice-ready tubs. Ideal for antipasti, burrata boards, and seasonal tomato programs.',
          pack_size: '2 x 1 kg tubs',
          units_per_case: 2,
          unit_weight_lbs: 2.2,
          case_weight_lbs: 4.4,
          uom: 'case',
          moq_cases: 2,
          temperature_zone: 'refrigerated',
          product_status: 'active',
          allergens: 'Milk',
          certifications: 'Vegetarian',
          is_sample_eligible: true,
          categoryId: IDS.categories.dairy,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.products,
        IDS.products.ricottaSalata,
        {
          sku: 'NS-RIC-6X500',
          product_name: 'Wildflower Ricotta Salata',
          brand: 'Northstar Reserve',
          short_description:
            'Bright, salty ricotta salata wedges for salads, pasta, and vegetable dishes.',
          long_description:
            'Firm ricotta salata with a clean sheep milk finish. Pre-sized wedges reduce prep and improve consistency.',
          pack_size: '6 x 500 g wedges',
          units_per_case: 6,
          unit_weight_lbs: 1.1,
          case_weight_lbs: 6.6,
          uom: 'case',
          moq_cases: 1,
          temperature_zone: 'refrigerated',
          product_status: 'active',
          allergens: 'Milk',
          certifications: 'Vegetarian, Gluten-Free',
          is_sample_eligible: true,
          categoryId: IDS.categories.dairy,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.products,
        IDS.products.chiliCrunch,
        {
          sku: 'NS-CHI-12X16',
          product_name: 'Calabrian Chili Crunch',
          brand: 'Northstar Pantry',
          short_description:
            'Sweet heat chili condiment for pizza, roasted vegetables, sandwiches, and brunch menus.',
          long_description:
            'Texture-driven chili crisp made with Calabrian peppers, shallots, and toasted garlic. Works across breakfast, lunch, and dinner menus.',
          pack_size: '12 x 16 oz jars',
          units_per_case: 12,
          unit_weight_lbs: 1,
          case_weight_lbs: 12,
          uom: 'case',
          moq_cases: 3,
          temperature_zone: 'ambient',
          product_status: 'active',
          allergens: 'None',
          certifications: 'Vegan, Gluten-Free',
          is_sample_eligible: true,
          categoryId: IDS.categories.pantry,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.products,
        IDS.products.demiGlace,
        {
          sku: 'NS-DEM-6X1L',
          product_name: 'Porcini Truffle Demi-Glace',
          brand: 'Northstar Pantry',
          short_description:
            'Rich ready-to-finish demi-glace with porcini depth and a subtle black truffle note.',
          long_description:
            'Chef-finished demi-glace for steak programs, short rib reductions, and banquet sauce work. Saves hours of reduction time without sacrificing depth.',
          pack_size: '6 x 1 L pouches',
          units_per_case: 6,
          unit_weight_lbs: 2.2,
          case_weight_lbs: 13.2,
          uom: 'case',
          moq_cases: 1,
          temperature_zone: 'frozen',
          product_status: 'active',
          allergens: 'Soy',
          certifications: 'Gluten-Free',
          is_sample_eligible: false,
          categoryId: IDS.categories.pantry,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.products,
        IDS.products.duckConfit,
        {
          sku: 'NS-DUC-2X5LB',
          product_name: 'Heritage Duck Confit Legs',
          brand: 'Northstar Reserve',
          short_description:
            'Fully prepared duck confit legs for tasting menus, banquets, and upscale brunch programs.',
          long_description:
            'Rendered and seasoned duck legs packed sous vide for clean thaw-and-fire execution in both fine dining and volume events.',
          pack_size: '2 x 5 lb bags',
          units_per_case: 2,
          unit_weight_lbs: 5,
          case_weight_lbs: 10,
          uom: 'case',
          moq_cases: 1,
          temperature_zone: 'frozen',
          product_status: 'active',
          allergens: 'None',
          certifications: 'No Antibiotics Ever',
          is_sample_eligible: true,
          categoryId: IDS.categories.proteins,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.products,
        IDS.products.bloodOrangeSorbet,
        {
          sku: 'NS-SOR-8X2.5L',
          product_name: 'Sicilian Blood Orange Sorbet',
          brand: 'Northstar Frozen',
          short_description:
            'Bright citrus sorbet with chef-friendly scooping texture and a clean finish.',
          long_description:
            'Blood orange sorbet with high fruit content and banquet-stable texture. Works for plated desserts, palate cleansers, and bar service.',
          pack_size: '8 x 2.5 L tubs',
          units_per_case: 8,
          unit_weight_lbs: 4.5,
          case_weight_lbs: 36,
          uom: 'case',
          moq_cases: 1,
          temperature_zone: 'frozen',
          product_status: 'active',
          allergens: 'None',
          certifications: 'Vegan, Dairy-Free, Gluten-Free',
          is_sample_eligible: true,
          categoryId: IDS.categories.frozen,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.products,
        IDS.products.fetaCrumble,
        {
          sku: 'NS-FET-4X2KG',
          product_name: 'Sheep & Goat Feta Crumble',
          brand: 'Northstar Reserve',
          short_description:
            'Pre-crumbled feta blend for salads, flatbreads, grain bowls, and breakfast items.',
          long_description:
            'Balanced sheep and goat milk feta crumble with a clean briny finish and low waste foodservice pack.',
          pack_size: '4 x 2 kg bags',
          units_per_case: 4,
          unit_weight_lbs: 4.4,
          case_weight_lbs: 17.6,
          uom: 'case',
          moq_cases: 1,
          temperature_zone: 'refrigerated',
          product_status: 'active',
          allergens: 'Milk',
          certifications: 'Vegetarian, Gluten-Free',
          is_sample_eligible: true,
          categoryId: IDS.categories.dairy,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.price_lists,
        IDS.priceLists.harbor,
        {
          price_list_name: 'Northstar Contract - Harbor Table Hospitality',
          price_list_type: 'contract',
          effective_start: daysFromNow(-45),
          effective_end: daysFromNow(120),
          is_active: true,
          notes:
            'Contract pricing for Harbor Table Hospitality Group spring/summer sourcing plan.',
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.price_lists,
        IDS.priceLists.cedar,
        {
          price_list_name: 'Northstar Contract - Cedar & Sage Catering',
          price_list_type: 'contract',
          effective_start: daysFromNow(-30),
          effective_end: daysFromNow(120),
          is_active: true,
          notes:
            'Catering-focused contract pricing with banquet dessert and pantry volume discounts.',
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.price_lists,
        IDS.priceLists.seabrook,
        {
          price_list_name: 'Northstar Contract - Seabrook Hotel Collection',
          price_list_type: 'contract',
          effective_start: daysFromNow(-60),
          effective_end: daysFromNow(150),
          is_active: true,
          notes:
            'Hotel banquet and in-room dining program pricing for Seabrook Hotel Collection.',
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.accounts,
        IDS.accounts.harbor,
        {
          account_name: 'Harbor Table Hospitality Group',
          account_type: 'restaurant',
          account_number: 'HT-1043',
          tax_exempt_number: null,
          is_tax_exempt: false,
          credit_status: 'good',
          credit_limit: 35000,
          notes:
            'Multi-location restaurant group focused on seasonal share plates and premium imported ingredients.',
          is_active: true,
          default_price_listId: IDS.priceLists.harbor,
          assigned_sales_repId: IDS.users.salesRep,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.accounts,
        IDS.accounts.cedar,
        {
          account_name: 'Cedar & Sage Catering Co.',
          account_type: 'caterer',
          account_number: 'CS-2088',
          tax_exempt_number: 'IL-EX-88431',
          is_tax_exempt: true,
          credit_status: 'good',
          credit_limit: 22000,
          notes:
            'Special events caterer with tasting menus, corporate trays, and off-premise banquet production.',
          is_active: true,
          default_price_listId: IDS.priceLists.cedar,
          assigned_sales_repId: IDS.users.salesRep,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.accounts,
        IDS.accounts.seabrook,
        {
          account_name: 'Seabrook Hotel Collection',
          account_type: 'hotel',
          account_number: 'SH-3320',
          tax_exempt_number: null,
          is_tax_exempt: false,
          credit_status: 'good',
          credit_limit: 50000,
          notes:
            'Hotel group operating banquets, lobby bar service, and in-room dining across two downtown properties.',
          is_active: true,
          default_price_listId: IDS.priceLists.seabrook,
          assigned_sales_repId: IDS.users.salesRep,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.contacts,
        IDS.contacts.maria,
        {
          contact_name: 'Maria Alvarez',
          email: 'maria.alvarez@harbortable.com',
          phone: '312-555-0141',
          role_title: 'Purchasing Director',
          is_primary: true,
          can_place_orders: true,
          can_see_invoices: true,
          is_active: true,
          accountId: IDS.accounts.harbor,
          locationId: null,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.contacts,
        IDS.contacts.owen,
        {
          contact_name: 'Owen Price',
          email: 'owen.price@harbortable.com',
          phone: '312-555-0170',
          role_title: 'Executive Chef',
          is_primary: false,
          can_place_orders: true,
          can_see_invoices: false,
          is_active: true,
          accountId: IDS.accounts.harbor,
          locationId: null,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.contacts,
        IDS.contacts.dana,
        {
          contact_name: 'Dana Kim',
          email: 'dana@cedarsagecatering.com',
          phone: '773-555-0123',
          role_title: 'Event Operations Manager',
          is_primary: true,
          can_place_orders: true,
          can_see_invoices: true,
          is_active: true,
          accountId: IDS.accounts.cedar,
          locationId: null,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.contacts,
        IDS.contacts.priya,
        {
          contact_name: 'Priya Raman',
          email: 'priya.raman@seabrookhotels.com',
          phone: '312-555-0162',
          role_title: 'Director of Banquets',
          is_primary: true,
          can_place_orders: true,
          can_see_invoices: true,
          is_active: true,
          accountId: IDS.accounts.seabrook,
          locationId: null,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.contacts,
        IDS.contacts.luca,
        {
          contact_name: 'Luca Moretti',
          email: 'luca.moretti@seabrookhotels.com',
          phone: '312-555-0165',
          role_title: 'Executive Sous Chef',
          is_primary: false,
          can_place_orders: true,
          can_see_invoices: false,
          is_active: true,
          accountId: IDS.accounts.seabrook,
          locationId: null,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.locations,
        IDS.locations.harborDowntown,
        {
          location_name: 'Harbor Table - Downtown',
          location_type: 'shipping',
          address_line_1: '145 West Kinzie Street',
          address_line_2: 'Receiving Dock A',
          city: 'Chicago',
          state: 'IL',
          postal_code: '60654',
          country: 'USA',
          delivery_instructions:
            'Deliver before 11:00 AM through dock A. Call purchasing on arrival.',
          is_active: true,
          accountId: IDS.accounts.harbor,
          default_contactId: IDS.contacts.maria,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.locations,
        IDS.locations.harborRiverNorth,
        {
          location_name: 'Harbor Table - River North',
          location_type: 'shipping',
          address_line_1: '302 North Wells Street',
          address_line_2: null,
          city: 'Chicago',
          state: 'IL',
          postal_code: '60654',
          country: 'USA',
          delivery_instructions:
            'Use alley entrance and confirm cold storage handoff with kitchen lead.',
          is_active: true,
          accountId: IDS.accounts.harbor,
          default_contactId: IDS.contacts.owen,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.locations,
        IDS.locations.cedarKitchen,
        {
          location_name: 'Cedar & Sage Production Kitchen',
          location_type: 'shipping',
          address_line_1: '4100 West Carroll Avenue',
          address_line_2: 'Suite 3',
          city: 'Chicago',
          state: 'IL',
          postal_code: '60624',
          country: 'USA',
          delivery_instructions:
            'Stage frozen pallets on rack 4 and dry goods at prep line entrance.',
          is_active: true,
          accountId: IDS.accounts.cedar,
          default_contactId: IDS.contacts.dana,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.locations,
        IDS.locations.seabrookMidtown,
        {
          location_name: 'Seabrook Hotel - Midtown Banquets',
          location_type: 'shipping',
          address_line_1: '800 North Michigan Avenue',
          address_line_2: 'Banquet Receiving',
          city: 'Chicago',
          state: 'IL',
          postal_code: '60611',
          country: 'USA',
          delivery_instructions:
            'Check in with banquet stewarding and label all banquet hold product.',
          is_active: true,
          accountId: IDS.accounts.seabrook,
          default_contactId: IDS.contacts.priya,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.locations,
        IDS.locations.seabrookWaterfront,
        {
          location_name: 'Seabrook Hotel - Waterfront',
          location_type: 'shipping',
          address_line_1: '1200 East Grand Avenue',
          address_line_2: 'Dock 2',
          city: 'Chicago',
          state: 'IL',
          postal_code: '60611',
          country: 'USA',
          delivery_instructions:
            'Morning deliveries only. Dock 2 access code provided to approved carriers.',
          is_active: true,
          accountId: IDS.accounts.seabrook,
          default_contactId: IDS.contacts.luca,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.contacts,
        IDS.contacts.maria,
        { locationId: IDS.locations.harborDowntown, updatedById: adminUser.id },
        transaction,
      );
      await upsertRecord(
        db.contacts,
        IDS.contacts.owen,
        {
          locationId: IDS.locations.harborRiverNorth,
          updatedById: adminUser.id,
        },
        transaction,
      );
      await upsertRecord(
        db.contacts,
        IDS.contacts.dana,
        { locationId: IDS.locations.cedarKitchen, updatedById: adminUser.id },
        transaction,
      );
      await upsertRecord(
        db.contacts,
        IDS.contacts.priya,
        {
          locationId: IDS.locations.seabrookMidtown,
          updatedById: adminUser.id,
        },
        transaction,
      );
      await upsertRecord(
        db.contacts,
        IDS.contacts.luca,
        {
          locationId: IDS.locations.seabrookWaterfront,
          updatedById: adminUser.id,
        },
        transaction,
      );

      const priceListItems = [
        [
          IDS.priceListItems.harborBurrata,
          IDS.priceLists.harbor,
          IDS.products.burrata,
          62,
          31,
          2,
        ],
        [
          IDS.priceListItems.harborRicotta,
          IDS.priceLists.harbor,
          IDS.products.ricottaSalata,
          48,
          8,
          1,
        ],
        [
          IDS.priceListItems.harborChili,
          IDS.priceLists.harbor,
          IDS.products.chiliCrunch,
          78,
          6.5,
          3,
        ],
        [
          IDS.priceListItems.harborDemi,
          IDS.priceLists.harbor,
          IDS.products.demiGlace,
          92,
          15.33,
          1,
        ],
        [
          IDS.priceListItems.harborDuck,
          IDS.priceLists.harbor,
          IDS.products.duckConfit,
          118,
          59,
          1,
        ],
        [
          IDS.priceListItems.harborSorbet,
          IDS.priceLists.harbor,
          IDS.products.bloodOrangeSorbet,
          72,
          9,
          1,
        ],
        [
          IDS.priceListItems.harborFeta,
          IDS.priceLists.harbor,
          IDS.products.fetaCrumble,
          58,
          14.5,
          1,
        ],
        [
          IDS.priceListItems.cedarBurrata,
          IDS.priceLists.cedar,
          IDS.products.burrata,
          66.5,
          33.25,
          2,
        ],
        [
          IDS.priceListItems.cedarRicotta,
          IDS.priceLists.cedar,
          IDS.products.ricottaSalata,
          50,
          8.33,
          1,
        ],
        [
          IDS.priceListItems.cedarChili,
          IDS.priceLists.cedar,
          IDS.products.chiliCrunch,
          81,
          6.75,
          3,
        ],
        [
          IDS.priceListItems.cedarDemi,
          IDS.priceLists.cedar,
          IDS.products.demiGlace,
          95,
          15.83,
          1,
        ],
        [
          IDS.priceListItems.cedarDuck,
          IDS.priceLists.cedar,
          IDS.products.duckConfit,
          121,
          60.5,
          1,
        ],
        [
          IDS.priceListItems.cedarSorbet,
          IDS.priceLists.cedar,
          IDS.products.bloodOrangeSorbet,
          69,
          8.63,
          1,
        ],
        [
          IDS.priceListItems.cedarFeta,
          IDS.priceLists.cedar,
          IDS.products.fetaCrumble,
          60,
          15,
          1,
        ],
        [
          IDS.priceListItems.seabrookBurrata,
          IDS.priceLists.seabrook,
          IDS.products.burrata,
          64,
          32,
          2,
        ],
        [
          IDS.priceListItems.seabrookRicotta,
          IDS.priceLists.seabrook,
          IDS.products.ricottaSalata,
          49,
          8.17,
          1,
        ],
        [
          IDS.priceListItems.seabrookChili,
          IDS.priceLists.seabrook,
          IDS.products.chiliCrunch,
          79,
          6.58,
          3,
        ],
        [
          IDS.priceListItems.seabrookDemi,
          IDS.priceLists.seabrook,
          IDS.products.demiGlace,
          94,
          15.67,
          1,
        ],
        [
          IDS.priceListItems.seabrookDuck,
          IDS.priceLists.seabrook,
          IDS.products.duckConfit,
          119,
          59.5,
          1,
        ],
        [
          IDS.priceListItems.seabrookSorbet,
          IDS.priceLists.seabrook,
          IDS.products.bloodOrangeSorbet,
          74,
          9.25,
          1,
        ],
        [
          IDS.priceListItems.seabrookFeta,
          IDS.priceLists.seabrook,
          IDS.products.fetaCrumble,
          59,
          14.75,
          1,
        ],
      ];

      for (const [
        id,
        priceListId,
        productId,
        casePrice,
        unitPrice,
        minCaseQty,
      ] of priceListItems) {
        await upsertRecord(
          db.price_list_items,
          id,
          {
            case_price: casePrice,
            unit_price: unitPrice,
            min_case_qty: minCaseQty,
            effective_start: daysFromNow(-30),
            effective_end: daysFromNow(120),
            price_listId: priceListId,
            productId,
            createdById: adminUser.id,
            updatedById: adminUser.id,
          },
          transaction,
        );
      }

      await upsertRecord(
        db.account_price_lists,
        IDS.accountPriceLists.harbor,
        {
          effective_start: daysFromNow(-45),
          effective_end: daysFromNow(120),
          is_primary: true,
          accountId: IDS.accounts.harbor,
          price_listId: IDS.priceLists.harbor,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.account_price_lists,
        IDS.accountPriceLists.cedar,
        {
          effective_start: daysFromNow(-30),
          effective_end: daysFromNow(120),
          is_primary: true,
          accountId: IDS.accounts.cedar,
          price_listId: IDS.priceLists.cedar,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.account_price_lists,
        IDS.accountPriceLists.seabrook,
        {
          effective_start: daysFromNow(-60),
          effective_end: daysFromNow(150),
          is_primary: true,
          accountId: IDS.accounts.seabrook,
          price_listId: IDS.priceLists.seabrook,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.quotes,
        IDS.quotes.harbor,
        {
          quote_number: 'QT-260501-HT',
          requested_at: daysFromNow(-6),
          expires_at: daysFromNow(12),
          quote_status: 'sent',
          quote_total: 202,
          notes:
            'Menu testing for new burrata and Calabrian chili shareables rollout.',
          accountId: IDS.accounts.harbor,
          locationId: IDS.locations.harborDowntown,
          requested_byId: IDS.users.buyerAdmin,
          ownerId: IDS.users.salesRep,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.quotes,
        IDS.quotes.cedar,
        {
          quote_number: 'QT-260428-CS',
          requested_at: daysFromNow(-9),
          expires_at: daysFromNow(5),
          quote_status: 'in_review',
          quote_total: 138,
          notes:
            'Dessert tasting package for June gala dessert station proposals.',
          accountId: IDS.accounts.cedar,
          locationId: IDS.locations.cedarKitchen,
          requested_byId: IDS.users.buyerAdmin,
          ownerId: IDS.users.salesRep,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.quotes,
        IDS.quotes.seabrook,
        {
          quote_number: 'QT-260423-SH',
          requested_at: daysFromNow(-14),
          expires_at: daysFromNow(3),
          quote_status: 'accepted',
          quote_total: 521,
          notes:
            'Accepted banquet menu pricing for duck confit and demi-glace sauce station.',
          accountId: IDS.accounts.seabrook,
          locationId: IDS.locations.seabrookMidtown,
          requested_byId: IDS.users.buyerAdmin,
          ownerId: IDS.users.salesRep,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      const quoteItems = [
        [
          IDS.quoteItems.harborBurrata,
          IDS.quotes.harbor,
          IDS.products.burrata,
          2,
          62,
          124,
          'Opening week share plate feature',
        ],
        [
          IDS.quoteItems.harborChili,
          IDS.quotes.harbor,
          IDS.products.chiliCrunch,
          1,
          78,
          78,
          'Pizza and brunch finish',
        ],
        [
          IDS.quoteItems.cedarSorbet,
          IDS.quotes.cedar,
          IDS.products.bloodOrangeSorbet,
          2,
          69,
          138,
          'Dessert station tasting',
        ],
        [
          IDS.quoteItems.seabrookDuck,
          IDS.quotes.seabrook,
          IDS.products.duckConfit,
          3,
          119,
          357,
          'Banquet plated entrée',
        ],
        [
          IDS.quoteItems.seabrookDemi,
          IDS.quotes.seabrook,
          IDS.products.demiGlace,
          2,
          82,
          164,
          'Banquet sauce station',
        ],
      ];

      for (const [
        id,
        quoteId,
        productId,
        quantityCases,
        casePrice,
        lineTotal,
        lineNotes,
      ] of quoteItems) {
        await upsertRecord(
          db.quote_items,
          id,
          {
            quantity_cases: quantityCases,
            case_price: casePrice,
            line_total: lineTotal,
            line_notes: lineNotes,
            quoteId,
            productId,
            createdById: adminUser.id,
            updatedById: adminUser.id,
          },
          transaction,
        );
      }

      await upsertRecord(
        db.sample_requests,
        IDS.sampleRequests.harbor,
        {
          sample_request_number: 'SR-260503-HT',
          sample_quantity: 1,
          requested_at: daysFromNow(-4),
          needed_by: daysFromNow(2),
          sample_status: 'approved',
          notes: 'Need for weekend LTO tasting with spring peas and mint.',
          accountId: IDS.accounts.harbor,
          locationId: IDS.locations.harborDowntown,
          requested_byId: IDS.users.buyerAdmin,
          productId: IDS.products.burrata,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.sample_requests,
        IDS.sampleRequests.cedar,
        {
          sample_request_number: 'SR-260505-CS',
          sample_quantity: 1,
          requested_at: daysFromNow(-2),
          needed_by: daysFromNow(4),
          sample_status: 'requested',
          notes: 'Client tasting for rooftop summer dessert menu.',
          accountId: IDS.accounts.cedar,
          locationId: IDS.locations.cedarKitchen,
          requested_byId: IDS.users.buyerAdmin,
          productId: IDS.products.bloodOrangeSorbet,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.sample_requests,
        IDS.sampleRequests.seabrook,
        {
          sample_request_number: 'SR-260430-SH',
          sample_quantity: 1,
          requested_at: daysFromNow(-7),
          needed_by: daysFromNow(1),
          sample_status: 'delivered',
          notes: 'Lobby bar spread test for mezze service.',
          accountId: IDS.accounts.seabrook,
          locationId: IDS.locations.seabrookWaterfront,
          requested_byId: IDS.users.buyerAdmin,
          productId: IDS.products.chiliCrunch,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      const savedLists = [
        [
          IDS.savedLists.harborWeekend,
          IDS.accounts.harbor,
          IDS.users.buyerAdmin,
          'Weekend brunch restock',
          'reorder',
          'Core Harbor Table mix for burrata boards, mezze, and Calabrian chili brunch stations.',
        ],
        [
          IDS.savedLists.harborChefCounter,
          IDS.accounts.harbor,
          IDS.users.buyer,
          'Chef counter tasting menu',
          'reorder',
          'Duck confit and blood orange sorbet kept ready for tasting-menu resets and VIP nights.',
        ],
        [
          IDS.savedLists.seabrookBanquet,
          IDS.accounts.seabrook,
          IDS.users.buyerAdmin,
          'Banquet sauce and antipasti set',
          'reorder',
          'Banquet-ready par list for demi-glace production and lobby lounge antipasti replenishment.',
        ],
      ];

      for (const [
        id,
        accountId,
        ownerId,
        listName,
        listType,
        notes,
      ] of savedLists) {
        await upsertRecord(
          db.saved_lists,
          id,
          {
            list_name: listName,
            list_type: listType,
            notes,
            accountId,
            ownerId,
            createdById: adminUser.id,
            updatedById: adminUser.id,
          },
          transaction,
        );
      }

      const savedListItems = [
        [
          IDS.savedListItems.harborWeekendBurrata,
          IDS.savedLists.harborWeekend,
          IDS.products.burrata,
          2,
          'Weekend burrata board prep',
        ],
        [
          IDS.savedListItems.harborWeekendChili,
          IDS.savedLists.harborWeekend,
          IDS.products.chiliCrunch,
          2,
          'Brunch pizza and egg station finish',
        ],
        [
          IDS.savedListItems.harborWeekendFeta,
          IDS.savedLists.harborWeekend,
          IDS.products.fetaCrumble,
          1,
          'Greek salad and mezze garnish',
        ],
        [
          IDS.savedListItems.harborChefCounterDuck,
          IDS.savedLists.harborChefCounter,
          IDS.products.duckConfit,
          1,
          'Chef counter duck confit course',
        ],
        [
          IDS.savedListItems.harborChefCounterSorbet,
          IDS.savedLists.harborChefCounter,
          IDS.products.bloodOrangeSorbet,
          2,
          'Sorbet reset for plated dessert finish',
        ],
        [
          IDS.savedListItems.seabrookBanquetDemi,
          IDS.savedLists.seabrookBanquet,
          IDS.products.demiGlace,
          2,
          'Banquet sauce station reserve',
        ],
        [
          IDS.savedListItems.seabrookBanquetBurrata,
          IDS.savedLists.seabrookBanquet,
          IDS.products.burrata,
          2,
          'Lobby lounge antipasti service',
        ],
      ];

      for (const [
        id,
        savedListId,
        productId,
        defaultQuantityCases,
        notes,
      ] of savedListItems) {
        const savedListItem = await upsertRecord(
          db.saved_list_items,
          id,
          {
            default_quantity_cases: defaultQuantityCases,
            notes,
            createdById: adminUser.id,
            updatedById: adminUser.id,
          },
          transaction,
        );

        await savedListItem.setSaved_list(savedListId, { transaction });
        await savedListItem.setProduct(productId, { transaction });
      }

      await upsertRecord(
        db.orders,
        IDS.orders.harborDelivered,
        {
          order_number: 'PO-260420-HT',
          po_number: 'HT-PO-4821',
          ordered_at: daysFromNow(-17),
          requested_delivery_date: daysFromNow(-14),
          promised_delivery_date: daysFromNow(-14),
          order_status: 'delivered',
          payment_terms: 'net_30',
          subtotal: 356,
          tax_total: 0,
          shipping_total: 0,
          order_total: 356,
          buyer_notes:
            'Restock for spring menu launch and weekend private dining buyout.',
          internal_notes: 'Delivered on time and received in full.',
          accountId: IDS.accounts.harbor,
          locationId: IDS.locations.harborDowntown,
          buyerId: IDS.users.buyerAdmin,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.orders,
        IDS.orders.harborSubmitted,
        {
          order_number: 'PO-260506-HT',
          po_number: 'HT-PO-4898',
          ordered_at: daysFromNow(-1),
          requested_delivery_date: daysFromNow(3),
          promised_delivery_date: null,
          order_status: 'submitted',
          payment_terms: 'net_30',
          subtotal: 262,
          tax_total: 0,
          shipping_total: 0,
          order_total: 262,
          buyer_notes:
            'Weekend event prep for chef counter menu and dessert cart.',
          internal_notes: null,
          accountId: IDS.accounts.harbor,
          locationId: IDS.locations.harborRiverNorth,
          buyerId: IDS.users.buyer,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      await upsertRecord(
        db.orders,
        IDS.orders.seabrookDelivered,
        {
          order_number: 'PO-260425-SH',
          po_number: 'SH-PO-9034',
          ordered_at: daysFromNow(-12),
          requested_delivery_date: daysFromNow(-9),
          promised_delivery_date: daysFromNow(-9),
          order_status: 'delivered',
          payment_terms: 'net_45',
          subtotal: 420,
          tax_total: 0,
          shipping_total: 0,
          order_total: 420,
          buyer_notes:
            'Banquet and in-room dining replenishment for spring conference block.',
          internal_notes: 'Priority delivery completed via dock 2.',
          accountId: IDS.accounts.seabrook,
          locationId: IDS.locations.seabrookMidtown,
          buyerId: IDS.users.buyerAdmin,
          createdById: adminUser.id,
          updatedById: adminUser.id,
        },
        transaction,
      );

      const orderItems = [
        [
          IDS.orderItems.harborDeliveredBurrata,
          IDS.orders.harborDelivered,
          IDS.products.burrata,
          2,
          62,
          124,
          'Burrata board program',
          'shipped',
        ],
        [
          IDS.orderItems.harborDeliveredChili,
          IDS.orders.harborDelivered,
          IDS.products.chiliCrunch,
          2,
          78,
          156,
          'Brunch and pizza stations',
          'shipped',
        ],
        [
          IDS.orderItems.harborDeliveredFeta,
          IDS.orders.harborDelivered,
          IDS.products.fetaCrumble,
          1,
          76,
          76,
          'Salad and mezze prep',
          'shipped',
        ],
        [
          IDS.orderItems.harborSubmittedDuck,
          IDS.orders.harborSubmitted,
          IDS.products.duckConfit,
          1,
          118,
          118,
          'Chef counter tasting menu',
          'pending',
        ],
        [
          IDS.orderItems.harborSubmittedSorbet,
          IDS.orders.harborSubmitted,
          IDS.products.bloodOrangeSorbet,
          2,
          72,
          144,
          'Dessert cart restock',
          'pending',
        ],
        [
          IDS.orderItems.seabrookDeliveredDemi,
          IDS.orders.seabrookDelivered,
          IDS.products.demiGlace,
          2,
          94,
          188,
          'Banquet sauce station',
          'shipped',
        ],
        [
          IDS.orderItems.seabrookDeliveredBurrata,
          IDS.orders.seabrookDelivered,
          IDS.products.burrata,
          2,
          64,
          128,
          'Lobby lounge antipasti',
          'shipped',
        ],
      ];

      for (const [
        id,
        orderId,
        productId,
        quantityCases,
        casePrice,
        lineTotal,
        lineNotes,
        fulfillmentStatus,
      ] of orderItems) {
        const orderItem = await upsertRecord(
          db.order_items,
          id,
          {
            quantity_cases: quantityCases,
            case_price: casePrice,
            line_total: lineTotal,
            fulfillment_status: fulfillmentStatus,
            line_notes: lineNotes,
            createdById: adminUser.id,
            updatedById: adminUser.id,
          },
          transaction,
        );

        await orderItem.setOrder(orderId, { transaction });
        await orderItem.setProduct(productId, { transaction });
      }
    });
  },

  async down(queryInterface, Sequelize) {
    const ids = [
      ...Object.values(IDS.orderItems),
      ...Object.values(IDS.orders),
      ...Object.values(IDS.savedListItems),
      ...Object.values(IDS.savedLists),
      ...Object.values(IDS.sampleRequests),
      ...Object.values(IDS.quoteItems),
      ...Object.values(IDS.quotes),
      ...Object.values(IDS.accountPriceLists),
      ...Object.values(IDS.priceListItems),
      ...Object.values(IDS.locations),
      ...Object.values(IDS.contacts),
      ...Object.values(IDS.accounts),
      ...Object.values(IDS.priceLists),
      ...Object.values(IDS.products),
      ...Object.values(IDS.categories),
      ...Object.values(IDS.users),
    ];

    await queryInterface.bulkDelete('order_items', {
      id: { [Sequelize.Op.in]: Object.values(IDS.orderItems) },
    });
    await queryInterface.bulkDelete('orders', {
      id: { [Sequelize.Op.in]: Object.values(IDS.orders) },
    });
    await queryInterface.bulkDelete('saved_list_items', {
      id: { [Sequelize.Op.in]: Object.values(IDS.savedListItems) },
    });
    await queryInterface.bulkDelete('saved_lists', {
      id: { [Sequelize.Op.in]: Object.values(IDS.savedLists) },
    });
    await queryInterface.bulkDelete('sample_requests', {
      id: { [Sequelize.Op.in]: Object.values(IDS.sampleRequests) },
    });
    await queryInterface.bulkDelete('quote_items', {
      id: { [Sequelize.Op.in]: Object.values(IDS.quoteItems) },
    });
    await queryInterface.bulkDelete('quotes', {
      id: { [Sequelize.Op.in]: Object.values(IDS.quotes) },
    });
    await queryInterface.bulkDelete('account_price_lists', {
      id: { [Sequelize.Op.in]: Object.values(IDS.accountPriceLists) },
    });
    await queryInterface.bulkDelete('price_list_items', {
      id: { [Sequelize.Op.in]: Object.values(IDS.priceListItems) },
    });
    await queryInterface.bulkDelete('locations', {
      id: { [Sequelize.Op.in]: Object.values(IDS.locations) },
    });
    await queryInterface.bulkDelete('contacts', {
      id: { [Sequelize.Op.in]: Object.values(IDS.contacts) },
    });
    await queryInterface.bulkDelete('accounts', {
      id: { [Sequelize.Op.in]: Object.values(IDS.accounts) },
    });
    await queryInterface.bulkDelete('price_lists', {
      id: { [Sequelize.Op.in]: Object.values(IDS.priceLists) },
    });
    await queryInterface.bulkDelete('products', {
      id: { [Sequelize.Op.in]: Object.values(IDS.products) },
    });
    await queryInterface.bulkDelete('product_categories', {
      id: { [Sequelize.Op.in]: Object.values(IDS.categories) },
    });
    await queryInterface.bulkDelete('users', {
      id: { [Sequelize.Op.in]: Object.values(IDS.users) },
    });

    await queryInterface.sequelize.query(
      `
        DELETE FROM "rolesPermissionsPermissions"
        WHERE ("roles_permissionsId", "permissionId") IN (
          SELECT r.id, p.id
          FROM roles r
          JOIN permissions p ON p.name IN ('CREATE_ORDERS', 'CREATE_ORDER_ITEMS')
          WHERE r.name IN ('Customer Buyer Admin', 'Customer Buyer')
        )
      `,
    );

    return ids;
  },
};
