const CompanyUser = require('../../../models/CompanyUser');
const User = require('../../../models/User');
const { logger } = require('../../../middleware/logger');

class CompanyUserRepository {
  constructor(unitOfWork) {
    this.unitOfWork = unitOfWork;
  }

  async create({ companyEmail, password, companyName, companyPhone, contactPersonName, contactPersonPhone }) {
    logger.info('CompanyUserRepository.create:start', { companyEmail, companyName });
    try {
      console.log('📊 CompanyUserRepository: Creating company user in database...');
      const hashedPassword = await User.hashPassword(password);

      const conn = this.unitOfWork.connection;
      // 1. Insert into users table
      const userQuery = `
        INSERT INTO users (email, password, user_type, role)
        VALUES (?, ?, 'company', 'user')
      `;
      const [userResult] = await conn.query(userQuery, [companyEmail, hashedPassword]);
      const userId = userResult.insertId;

      logger.info('CompanyUserRepository.create:user_created', { userId });
      console.log('✅ User record created with ID:', userId);

      // 2. Insert into company_profiles table
      const profileQuery = `
        INSERT INTO company_profiles (user_id, company_name, phone, contact_person_name, contact_person_phone)
        VALUES (?, ?, ?, ?, ?)
      `;
      await conn.query(profileQuery, [
        userId,
        companyName,
        companyPhone,
        contactPersonName,
        contactPersonPhone
      ]);

      logger.info('CompanyUserRepository.create:profile_created', { userId, companyName });
      console.log('✅ Company profile created');

      logger.info('CompanyUserRepository.create:success', { userId });
      return new CompanyUser(
        userId,
        companyEmail,
        hashedPassword,
        companyName,
        companyPhone,
        contactPersonName,
        contactPersonPhone,
        null, // registrationNumber is now null at registration
        new Date()
      );
    } catch (error) {
      logger.error('CompanyUserRepository.create:error', { error: error.message });
      throw error;
    }
  }

  async findByEmail(email) {
    logger.info('CompanyUserRepository.findByEmail:start', { email });
    try {
      console.log('🔍 CompanyUserRepository: Querying database for company user...');
      const conn = this.unitOfWork.connection;
      const query = `
        SELECT u.*, cp.company_name, cp.registration_number, cp.phone as company_phone, 
               cp.contact_person_name
        FROM users u
        LEFT JOIN company_profiles cp ON u.id = cp.user_id
        WHERE u.email = ? AND u.user_type = 'company'
      `;
      const [rows] = await conn.query(query, [email]);
      if (rows.length > 0) {
        logger.info('CompanyUserRepository.findByEmail:found', { email, userId: rows[0].id });
        const row = rows[0];
        return new CompanyUser(
          row.id,
          row.email,
          row.password,
          row.company_name,
          row.company_phone,
          row.contact_person_name,
          null,
          row.registration_number,
          row.created_at,
          row.updated_at
        );
      }
      logger.info('CompanyUserRepository.findByEmail:not_found', { email });
      return null;
    } catch (error) {
      logger.error('CompanyUserRepository.findByEmail:error', { email, error: error.message });
      throw error;
    }
  }

  async findById(userId) {
    logger.info('CompanyUserRepository.findById:start', { userId });
    try {
      console.log('🔍 CompanyUserRepository: Querying database for company user by ID...');
      const conn = this.unitOfWork.connection;
      const query = `
        SELECT u.*, cp.company_name, cp.registration_number, cp.phone as company_phone, 
               cp.contact_person_name
        FROM users u
        LEFT JOIN company_profiles cp ON u.id = cp.user_id
        WHERE u.id = ? AND u.user_type = 'company'
      `;
      const [rows] = await conn.query(query, [userId]);
      if (rows.length > 0) {
        logger.info('CompanyUserRepository.findById:found', { userId });
        const row = rows[0];
        return new CompanyUser(
          row.id,
          row.email,
          row.password,
          row.company_name,
          row.company_phone,
          row.contact_person_name,
          null,
          row.registration_number,
          row.created_at,
          row.updated_at
        );
      }
      logger.info('CompanyUserRepository.findById:not_found', { userId });
      return null;
    } catch (error) {
      logger.error('CompanyUserRepository.findById:error', { userId, error: error.message });
      throw error;
    }
  }

  async updateProfileAndMarkCompleted(userId, profileData) {
    logger.info('CompanyUserRepository.updateProfileAndMarkCompleted:start', { userId });
    try {
      console.log('Updating profile and marking registration as completed for user ID:', userId);
      const conn = this.unitOfWork.connection;
      const {
        address,
        zip_code,
        city,
        country, // Add country here
        branch,
        numberOfEmployees,
        registrationNumber,
        atuNumber,
        businessType,
        iban,
        accountHolderName,
        companyName,
        companyPhone,
        contactPersonName,
        contactPersonPhone
      } = profileData;

      await conn.query(
        `INSERT INTO company_profiles (
          user_id, company_name, registration_number, atu_number, phone, address, zip_code, city, country,
          branch, number_of_employees, business_type, contact_person_name, contact_person_phone, account_holder_name
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE
          company_name = VALUES(company_name),
          registration_number = VALUES(registration_number),
          atu_number = VALUES(atu_number),
          phone = VALUES(phone),
          address = VALUES(address),
          zip_code = VALUES(zip_code),
          city = VALUES(city),
          country = VALUES(country),
          branch = VALUES(branch),
          number_of_employees = VALUES(number_of_employees),
          business_type = VALUES(business_type),
          contact_person_name = VALUES(contact_person_name),
          contact_person_phone = VALUES(contact_person_phone),
          account_holder_name = VALUES(account_holder_name)`,
        [
          userId,
          companyName,
          registrationNumber || null,
          atuNumber || null,
          companyPhone || null,
          address || null,
          zip_code || null,
          city || null,
          country || null,
          branch || null,
          numberOfEmployees || null,
          businessType || null,
          contactPersonName || null,
          contactPersonPhone || null,
          accountHolderName || null
        ]
      );

      logger.info('CompanyUserRepository.updateProfileAndMarkCompleted:profile_updated', { userId });

      // Update IBAN in users table if provided
      if (iban) {
        await conn.query(
          `UPDATE users SET iban = ? WHERE id = ?`,
          [iban, userId]
        );
        logger.info('CompanyUserRepository.updateProfileAndMarkCompleted:iban_updated', { userId });
      }

      await conn.query(
        `UPDATE user_status SET profile_completed = 1, profile_completed_at = NOW() WHERE user_id = ?`,
        [userId]
      );

      logger.info('CompanyUserRepository.updateProfileAndMarkCompleted:profile_completed', { userId });
    } catch (error) {
      logger.error('CompanyUserRepository.updateProfileAndMarkCompleted:error', { userId, error: error.message });
      throw error;
    }
  }


}

module.exports = CompanyUserRepository;