module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('plans', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
        allowNull: false,
      },
      name: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      price: {
        type: Sequelize.DECIMAL(10, 2),
        allowNull: false,
        defaultValue: 0,
      },
      features: {
        type: Sequelize.JSONB,
        allowNull: true,
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
    });

    await queryInterface.addColumn('businesses', 'planId', {
      type: Sequelize.UUID,
      allowNull: true,
      references: {
        model: 'plans',
        key: 'id',
      },
      onUpdate: 'CASCADE',
      onDelete: 'SET NULL',
    });

    await queryInterface.addColumn('businesses', 'renewal_date', {
      type: Sequelize.DATE,
      allowNull: true,
    });

    // Seed basic plans
    const now = new Date();
    const plans = [
      {
        id: '00000000-0000-0000-0000-000000000001',
        name: 'Basic (Free)',
        price: 0,
        features: JSON.stringify(['Limited Leads', 'Standard Listing']),
        createdAt: now,
        updatedAt: now,
      },
      {
        id: '00000000-0000-0000-0000-000000000002',
        name: 'Professional',
        price: 49.99,
        features: JSON.stringify(['Unlimited Leads', 'Priority Support', 'Enhanced Profile']),
        createdAt: now,
        updatedAt: now,
      },
      {
        id: '00000000-0000-0000-0000-000000000003',
        name: 'Enterprise',
        price: 199.99,
        features: JSON.stringify(['Custom Branding', 'API Access', 'Dedicated Manager']),
        createdAt: now,
        updatedAt: now,
      },
    ];

    await queryInterface.bulkInsert('plans', plans);

    // Assign free plan to existing businesses
    await queryInterface.sequelize.query(
      `UPDATE businesses SET "planId" = '00000000-0000-0000-0000-000000000001', "renewal_date" = '${new Date(now.getFullYear(), now.getMonth() + 1, now.getDate()).toISOString()}'`
    );
  },

  down: async (queryInterface, Sequelize) => {
    await queryInterface.removeColumn('businesses', 'planId');
    await queryInterface.removeColumn('businesses', 'renewal_date');
    await queryInterface.dropTable('plans');
  },
};
