import { google } from 'googleapis'
import type { Order } from '@prisma/client'

const SHEET_NAME = 'Comandes'

const HEADERS = [
  'Núm. Comanda', 'Data', 'Estat', 'Producte',
  'Talla Samarreta', 'Talla Mitjons',
  'Nom', 'Cognoms', 'Email', 'Telèfon',
  'Lliurament', 'Adreça', 'CP', 'Població', 'Província',
  'Base (€)', 'Enviament (€)', 'Total (€)',
]

const PRODUCT_NAMES: Record<string, string> = {
  samarreta: 'Samarreta',
  mitjons: 'Mitjons',
  pack: 'Pack S+M',
}

const STATUS_LABELS: Record<string, string> = {
  PENDING: 'Pendent',
  PAID: 'Pagat',
  PREPARING: 'Preparant',
  SHIPPED: 'Enviat',
  DELIVERED: 'Lliurat',
  CANCELLED: 'Cancel·lat',
}

function getAuth() {
  const b64 = process.env.GOOGLE_CREDENTIALS_BASE64
  if (!b64) throw new Error('GOOGLE_CREDENTIALS_BASE64 no configurada')
  const credentials = JSON.parse(Buffer.from(b64, 'base64').toString('utf-8'))
  return new google.auth.GoogleAuth({
    credentials,
    scopes: ['https://www.googleapis.com/auth/spreadsheets'],
  })
}

function orderToRow(order: Order): string[] {
  return [
    order.orderNumber,
    new Date(order.createdAt).toLocaleDateString('ca-ES', {
      day: '2-digit', month: '2-digit', year: 'numeric',
      hour: '2-digit', minute: '2-digit',
    }),
    STATUS_LABELS[order.status] ?? order.status,
    PRODUCT_NAMES[order.product] ?? order.product,
    order.sizeTshirt ?? '',
    order.sizeSocks ?? '',
    order.nom,
    order.cognoms,
    order.email,
    order.telefon,
    order.shipping === 'correos' ? 'Correos Express' : 'Recollida Corbins/Lleida',
    order.adreca ?? '',
    order.codiPostal ?? '',
    order.poblacio ?? '',
    order.provincia ?? '',
    order.baseAmount.toFixed(2).replace('.', ','),
    order.shippingAmount.toFixed(2).replace('.', ','),
    order.totalAmount.toFixed(2).replace('.', ','),
  ]
}

async function ensureHeaders(sheets: ReturnType<typeof google.sheets>, sheetId: string) {
  const res = await sheets.spreadsheets.values.get({
    spreadsheetId: sheetId,
    range: `${SHEET_NAME}!A1:R1`,
  })
  const firstRow = res.data.values?.[0]
  if (!firstRow || firstRow[0] !== HEADERS[0]) {
    await sheets.spreadsheets.values.update({
      spreadsheetId: sheetId,
      range: `${SHEET_NAME}!A1`,
      valueInputOption: 'RAW',
      requestBody: { values: [HEADERS] },
    })
  }
}

export async function appendOrderToSheet(order: Order) {
  const sheetId = process.env.GOOGLE_SHEET_ID
  if (!sheetId || !process.env.GOOGLE_CREDENTIALS_BASE64) return

  const auth = getAuth()
  const sheets = google.sheets({ version: 'v4', auth })

  await ensureHeaders(sheets, sheetId)

  await sheets.spreadsheets.values.append({
    spreadsheetId: sheetId,
    range: `${SHEET_NAME}!A:R`,
    valueInputOption: 'RAW',
    insertDataOption: 'INSERT_ROWS',
    requestBody: { values: [orderToRow(order)] },
  })
}

export async function syncAllOrdersToSheet(orders: Order[]) {
  const sheetId = process.env.GOOGLE_SHEET_ID
  if (!sheetId || !process.env.GOOGLE_CREDENTIALS_BASE64) return

  const auth = getAuth()
  const sheets = google.sheets({ version: 'v4', auth })

  // Clear and rewrite all data
  await sheets.spreadsheets.values.clear({
    spreadsheetId: sheetId,
    range: `${SHEET_NAME}!A:R`,
  })

  const rows = [HEADERS, ...orders.map(orderToRow)]

  await sheets.spreadsheets.values.update({
    spreadsheetId: sheetId,
    range: `${SHEET_NAME}!A1`,
    valueInputOption: 'RAW',
    requestBody: { values: rows },
  })

  return rows.length - 1
}
