import { Injectable, BadRequestException } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { InvoiceIssuer } from './entities/invoice_issuer.entity';

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

  async findAll() {
    return await this.dataSource.query(`
            SELECT ii.*, s.state_name 
            FROM invoice_issuers ii
            LEFT JOIN state s ON ii.state_id = s.state_id
            ORDER BY ii.created_at DESC
        `);
  }

  async findOne(id: number) {
    const [issuer] = await this.dataSource.query(
      `
            SELECT ii.*, s.state_name 
            FROM invoice_issuers ii
            LEFT JOIN state s ON ii.state_id = s.state_id
            WHERE ii.id = ?
        `,
      [id],
    );
    if (!issuer) throw new BadRequestException('Invoice Issuer not found');
    return issuer;
  }

  async create(data: any) {
    // If setting as default, unset others
    if (data.is_default) {
      await this.dataSource.query('UPDATE invoice_issuers SET is_default = 0');
    }

    const result = await this.dataSource.query(
      `INSERT INTO invoice_issuers 
      (company_name, invoice_prefix, gstin, registered_address, state_id, email, phone, logo_url, is_default, is_active, pan, cin, msme_no, city_id, declaration_text, jurisdiction_text, footer_note) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        data.company_name,
        data.invoice_prefix,
        data.gstin,
        data.registered_address,
        data.state_id,
        data.email,
        data.phone,
        data.logo_url,
        data.is_default || 0,
        data.is_active ?? 1,
        data.pan || null,
        data.cin || null,
        data.msme_no || null,
        data.city_id || null,
        data.declaration_text || null,
        data.jurisdiction_text || null,
        data.footer_note || null,
      ],
    );

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

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

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

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

    const fields = [
      'company_name',
      'invoice_prefix',
      'gstin',
      'registered_address',
      'state_id',
      'email',
      'phone',
      'logo_url',
      'is_default',
      'is_active',
      'pan',
      'cin',
      'msme_no',
      'city_id',
      'declaration_text',
      'jurisdiction_text',
      'footer_note',
    ];

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

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

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

    return { ...issuer, ...data };
  }

  async remove(id: number) {
    const issuer = await this.findOne(id);
    if (issuer.is_default) {
      throw new BadRequestException('Default issuer cannot be deleted');
    }
    await this.dataSource.query('DELETE FROM invoice_issuers WHERE id = ?', [
      id,
    ]);
    return { success: true };
  }
}
