import { google } from 'googleapis';

const auth = new google.auth.GoogleAuth({
  credentials: {
    client_email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
    private_key: process.env.GOOGLE_PRIVATE_KEY?.replace(/\\n/g, '\n'),
  },
  scopes: ['https://www.googleapis.com/auth/spreadsheets'],
});

const sheets = google.sheets({ version: 'v4', auth });
const SPREADSHEET_ID = process.env.GOOGLE_SHEET_ID;

export async function emailExists(email: string): Promise<boolean> {
  const formula = `=COUNTIF(G:G,"${email}")`;

  // Escribir fórmula en celda auxiliar
  await sheets.spreadsheets.values.update({
    spreadsheetId: SPREADSHEET_ID,
    range: 'VOLUNTARIOS!Z1', // usa una columna libre
    valueInputOption: 'USER_ENTERED',
    requestBody: {
      values: [[formula]],
    },
  });

  // Leer resultado calculado
  const result = await sheets.spreadsheets.values.get({
    spreadsheetId: SPREADSHEET_ID,
    range: 'VOLUNTARIOS!Z1',
    valueRenderOption: 'UNFORMATTED_VALUE',
  });

  const count = result.data.values?.[0]?.[0] || 0;

  return Number(count) > 0;
}


export async function getVolunteerCount(): Promise<number> {
  const result = await sheets.spreadsheets.values.get({
    spreadsheetId: SPREADSHEET_ID,
    range: 'VOLUNTARIOS!B2:B', // columna nombre_completo, se llena en cada registro
    valueRenderOption: 'UNFORMATTED_VALUE',
  });

  const rows = result.data.values || [];
  return rows.filter((row) => row[0] !== undefined && row[0] !== '').length;
}

export async function appendToSheet(values: any[]) {
  try {
    await sheets.spreadsheets.values.append({
      spreadsheetId: SPREADSHEET_ID,
      range: 'VOLUNTARIOS!A2:H2',
      valueInputOption: 'RAW',
      requestBody: {
        values: [values],
      },
    });

    return {
      success: true,
      message: 'Registro guardado correctamente',
    };

  } catch (error) {
    throw error;
  }
}

export async function appendRegistrationToSheet(values: string[]) {
  try {
    await sheets.spreadsheets.values.append({
      spreadsheetId: SPREADSHEET_ID,
      range: 'VOLUNTARIOS!A2:AV',
      valueInputOption: 'RAW',
      requestBody: {
        values: [values],
      },
    });

    return { success: true, message: 'Registro guardado correctamente' };
  } catch (error) {
    throw error;
  }
}
