import { Injectable, BadRequestException } from '@nestjs/common';
import { DataSource } from 'typeorm';

@Injectable()
export class IssuerBankAccountsService {
  constructor(private dataSource: DataSource) {}

  async findAll(issuerId: number) {
    return await this.dataSource.query(
      `SELECT * FROM issuer_bank_accounts WHERE invoice_issuer_id = ? ORDER BY is_default DESC, created_at DESC`,
      [issuerId],
    );
  }

  async findOne(id: number) {
    const [account] = await this.dataSource.query(
      `SELECT * FROM issuer_bank_accounts WHERE id = ?`,
      [id],
    );
    if (!account) throw new BadRequestException('Bank account not found');
    return account;
  }

  async create(data: any) {
    // If setting as default, unset others for this issuer
    if (data.is_default) {
      await this.dataSource.query(
        'UPDATE issuer_bank_accounts SET is_default = 0 WHERE invoice_issuer_id = ?',
        [data.invoice_issuer_id],
      );
    }

    const result = await this.dataSource.query(
      `INSERT INTO issuer_bank_accounts 
            (invoice_issuer_id, account_name, bank_name, branch, account_number, ifsc_code, swift_code, is_default, is_active) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        data.invoice_issuer_id,
        data.account_name,
        data.bank_name,
        data.branch || null,
        data.account_number,
        data.ifsc_code,
        data.swift_code || null,
        data.is_default || 0,
        data.is_active ?? 1,
      ],
    );

    return { id: result.insertId, ...data };
  }

  async update(id: number, data: any) {
    const account = await this.findOne(id);

    // If setting as default, unset others for this issuer
    if (data.is_default) {
      await this.dataSource.query(
        'UPDATE issuer_bank_accounts SET is_default = 0 WHERE invoice_issuer_id = ? AND id != ?',
        [account.invoice_issuer_id, id],
      );
    }

    const updateFields = [];
    const values = [];

    const fields = [
      'account_name',
      'bank_name',
      'branch',
      'account_number',
      'ifsc_code',
      'swift_code',
      'is_default',
      'is_active',
    ];

    for (const field of fields) {
      if (data[field] !== undefined) {
        updateFields.push(`${field} = ?`);
        values.push(data[field]);
      }
    }

    if (updateFields.length === 0) return account;

    values.push(id);
    await this.dataSource.query(
      `UPDATE issuer_bank_accounts SET ${updateFields.join(', ')} WHERE id = ?`,
      values,
    );

    return { ...account, ...data };
  }

  async remove(id: number) {
    await this.dataSource.query(
      'DELETE FROM issuer_bank_accounts WHERE id = ?',
      [id],
    );
    return { success: true };
  }
}
