export default {
  register() {},
  async bootstrap({ strapi }: { strapi: any }) {
    // Grant public access to product collection
    const publicRole = await strapi
      .query('plugin::users-permissions.role')
      .findOne({ where: { type: 'public' } });

    if (publicRole) {
      const actions = ['api::product.product.find', 'api::product.product.findOne'];

      for (const action of actions) {
        const exists = await strapi
          .query('plugin::users-permissions.permission')
          .findOne({ where: { action, role: publicRole.id } });

        if (!exists) {
          await strapi.query('plugin::users-permissions.permission').create({
            data: { action, role: publicRole.id },
          });
        }
      }
    }

    // Add a sample product if none exist
    const productCount = await strapi.documents('api::product.product').count();
    if (productCount === 0) {
      await strapi.documents('api::product.product').create({
        data: {
          name: 'Classic T-Shirt',
          description: 'A comfortable, high-quality cotton t-shirt.',
          price: 29.99,
          stock: 100,
        },
        status: 'published',
        locale: 'en',
      });
      console.log('Sample product created via Document Service!');
    }
  },
};
