'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [companies, users] = await Promise.all([
      queryInterface.sequelize.query("SELECT id FROM company WHERE code = 'COMP001' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id FROM user WHERE username = 'admin' LIMIT 1")
    ]);

    if (companies[0].length === 0 || users[0].length === 0) return;

    const companyId = companies[0][0].id;
    const userId = users[0][0].id;

    const currentDate = new Date();
    const currentYear = currentDate.getFullYear();
    const nextYear = currentYear + 1;
    
    // Determine fiscal year based on current date
    let startYear = currentYear;
    let endYear = nextYear;
    let startDate = `${startYear}-04-01`;
    let endDate = `${endYear}-03-31`;

    // If current date is before April 1, use previous year
    if (currentDate.getMonth() < 3 || (currentDate.getMonth() === 3 && currentDate.getDate() < 1)) {
      startYear = currentYear - 1;
      endYear = currentYear;
      startDate = `${startYear}-04-01`;
      endDate = `${endYear}-03-31`;
    }

    const dialect = queryInterface.sequelize.getDialect ? queryInterface.sequelize.getDialect() : 'mysql';
    const yearCode = `${startYear}-${endYear}`;
    if (dialect === 'mysql' || dialect === 'mariadb') {
      await queryInterface.sequelize.query(
        `INSERT IGNORE INTO fiscal_year (company_id, fiscal_year, start_date, end_date, is_closed, status, created_by, created_at, updated_at)
         VALUES (:company_id, :fiscal_year, :start_date, :end_date, 0, 'ACTIVE', :created_by, NOW(), NOW())`,
        { replacements: { company_id: companyId, fiscal_year: yearCode, start_date: startDate, end_date: endDate, created_by: userId } }
      );
    } else {
      await queryInterface.bulkInsert('fiscal_year', [{
        company_id: companyId,
        fiscal_year: yearCode,
        start_date: startDate,
        end_date: endDate,
        is_closed: false,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      }], { ignoreDuplicates: true });
    }
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.bulkDelete('fiscal_year', null, {});
  }
};

