import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest'

// Standard WS/notification mocks (same as the other public-app route tests).
vi.mock('../../src/plugins/websocket.js', () => ({
  sendToUser: vi.fn(() => false),
  sendToSessionParticipant: vi.fn(() => false),
  registerWebSocketPlugin: vi.fn(async () => {}),
  registerWebSocketRoute: vi.fn(),
  isUserOnlineWs: vi.fn(() => false),
  getSessionConnections: vi.fn(() => ({})),
}))
vi.mock('../../src/services/notification.service.js', () => ({
  sendPushNotification: vi.fn(async () => true),
  registerDeviceToken: vi.fn(async () => {}),
}))

const { buildPublic } = await import('../helpers/server.js')
const { resetDb, resetAppConfig, db } = await import('../helpers/db.js')
const { createCustomer } = await import('../helpers/fixtures.js')
const { PaymentRequestStatus } = await import('../../src/constants.js')
const { requestPayment } = await import('../../src/services/payment.service.js')

const WEBHOOK_TOKEN = 'test-webhook-token-abcdefghijklmnop'

const fireWebhook = (app, body, token = WEBHOOK_TOKEN) =>
  app.inject({
    method: 'POST',
    url: '/api/shared/payment/webhooks/xendit',
    headers: { 'x-callback-token': token, 'content-type': 'application/json' },
    payload: body,
  })

describe('POST /api/shared/payment/webhooks/xendit', () => {
  let app
  let customer

  beforeAll(async () => {
    vi.stubEnv('XENDIT_WEBHOOK_TOKEN', WEBHOOK_TOKEN)
    await resetAppConfig()
    app = await buildPublic()
  })

  beforeEach(async () => {
    await resetDb()
    const phone = `+628${Math.floor(Math.random() * 1e10).toString().padStart(10, '0')}`
    customer = await createCustomer({ callName: 'XenditTester', phone })
  })

  afterAll(async () => {
    await app?.close()
    vi.unstubAllEnvs()
  })

  it('401s when x-callback-token is missing or wrong', async () => {
    const session = await requestPayment({
      productType: 'chat_session',
      customerId: customer.id,
      durationMinutes: 12,
      amount: 50_000,
    })

    const wrong = await fireWebhook(app, {
      id: 'inv_x', external_id: session.id, status: 'PAID', amount: 50_000,
    }, 'totally-wrong-token-of-same-shape-len')
    expect(wrong.statusCode).toBe(401)

    const missing = await app.inject({
      method: 'POST',
      url: '/api/shared/payment/webhooks/xendit',
      payload: { id: 'inv_x', external_id: session.id, status: 'PAID', amount: 50_000 },
    })
    expect(missing.statusCode).toBe(401)
  })

  it('PAID confirms pending request and stamps xendit_* columns', async () => {
    const session = await requestPayment({
      productType: 'chat_session',
      customerId: customer.id,
      durationMinutes: 12,
      amount: 50_000,
    })

    const res = await fireWebhook(app, {
      id: 'inv_abc', external_id: session.id, status: 'PAID', amount: 50_000, payment_method: 'BCA',
    })
    expect(res.statusCode).toBe(200)
    expect(res.json().ok).toBe(true)

    const [row] = await db()`
      SELECT status, confirmed_at, xendit_invoice_id, xendit_payment_method, xendit_paid_amount
      FROM payment_requests WHERE id = ${session.id}
    `
    expect(row.status).toBe(PaymentRequestStatus.CONFIRMED)
    expect(row.confirmed_at).not.toBeNull()
    expect(row.xendit_invoice_id).toBe('inv_abc')
    expect(row.xendit_payment_method).toBe('BCA')
    expect(row.xendit_paid_amount).toBe(50_000)
  })

  it('PAID with amount mismatch returns 409 and leaves row pending', async () => {
    const session = await requestPayment({
      productType: 'chat_session',
      customerId: customer.id, durationMinutes: 12, amount: 50_000,
    })

    const res = await fireWebhook(app, {
      id: 'inv_bad', external_id: session.id, status: 'PAID', amount: 999,
    })
    expect(res.statusCode).toBe(409)
    expect(res.json().error).toBe('amount_mismatch')

    const [row] = await db()`SELECT status, xendit_invoice_id FROM payment_requests WHERE id = ${session.id}`
    expect(row.status).toBe(PaymentRequestStatus.PENDING)
    expect(row.xendit_invoice_id).toBeNull()
  })

  it('idempotent: second PAID delivery for the same row ACKs without erroring', async () => {
    const session = await requestPayment({
      productType: 'chat_session',
      customerId: customer.id, durationMinutes: 12, amount: 50_000,
    })

    const first = await fireWebhook(app, {
      id: 'inv_dup', external_id: session.id, status: 'PAID', amount: 50_000, payment_method: 'BCA',
    })
    expect(first.statusCode).toBe(200)

    const second = await fireWebhook(app, {
      id: 'inv_dup', external_id: session.id, status: 'PAID', amount: 50_000, payment_method: 'BCA',
    })
    expect(second.statusCode).toBe(200)
    expect(second.json().ok).toBe(true)

    const [row] = await db()`SELECT status FROM payment_requests WHERE id = ${session.id}`
    expect(row.status).toBe(PaymentRequestStatus.CONFIRMED)
  })

  it('EXPIRED flips pending → expired (idempotent on repeat)', async () => {
    const session = await requestPayment({
      productType: 'chat_session',
      customerId: customer.id, durationMinutes: 12, amount: 50_000,
    })

    const res = await fireWebhook(app, {
      id: 'inv_exp', external_id: session.id, status: 'EXPIRED',
    })
    expect(res.statusCode).toBe(200)

    const [row] = await db()`SELECT status FROM payment_requests WHERE id = ${session.id}`
    expect(row.status).toBe(PaymentRequestStatus.EXPIRED)

    // Second delivery is a no-op (WHERE status = 'pending' filters it out)
    const repeat = await fireWebhook(app, {
      id: 'inv_exp', external_id: session.id, status: 'EXPIRED',
    })
    expect(repeat.statusCode).toBe(200)
  })

  it('unknown external_id ACKs without 5xx so Xendit stops retrying', async () => {
    const res = await fireWebhook(app, {
      id: 'inv_orphan',
      external_id: '00000000-0000-0000-0000-000000000000',
      status: 'PAID',
      amount: 50_000,
    })
    expect(res.statusCode).toBe(200)
    expect(res.json().ignored).toBe('unknown_payment_request')
  })

  it('missing external_id ACKs (forward-compat for non-Invoice event types)', async () => {
    const res = await fireWebhook(app, { id: 'evt_x', status: 'SOMETHING_ELSE' })
    expect(res.statusCode).toBe(200)
    expect(res.json().ignored).toBe('no_external_id')
  })

  it('unhandled status ACKs as ignored', async () => {
    const session = await requestPayment({
      productType: 'chat_session',
      customerId: customer.id, durationMinutes: 12, amount: 50_000,
    })
    const res = await fireWebhook(app, {
      id: 'inv_partial', external_id: session.id, status: 'PARTIAL_REFUND', amount: 50_000,
    })
    expect(res.statusCode).toBe(200)
    expect(res.json().ignored).toBe('PARTIAL_REFUND')

    const [row] = await db()`SELECT status FROM payment_requests WHERE id = ${session.id}`
    expect(row.status).toBe(PaymentRequestStatus.PENDING)
  })

  // --- Survival logging --------------------------------------------------
  // Every inbound webhook lands in `webhook_logs` BEFORE auth/validation, so
  // we keep a forensic record on rejects, unknown payments, and exceptions.
  describe('webhook_logs survival audit', () => {
    const latestLog = async () => {
      const rows = await db()`SELECT * FROM webhook_logs ORDER BY received_at DESC LIMIT 1`
      return rows[0]
    }

    it('PAID: logs row with parsed primary fields + outcome stamped', async () => {
      const session = await requestPayment({
        productType: 'chat_session',
        customerId: customer.id, durationMinutes: 12, amount: 50_000,
      })

      await fireWebhook(app, {
        id: 'inv_log_paid',
        external_id: session.id,
        status: 'PAID',
        amount: 50_000,
        currency: 'IDR',
        payment_method: 'BCA',
        paid_at: '2026-05-25T10:00:00.000Z',
        metadata: { app: 'halobestie_v2' },
      })

      const log = await latestLog()
      expect(log.provider).toBe('xendit')
      expect(log.callback_token_valid).toBe(true)
      expect(log.xendit_event_id).toBe('inv_log_paid')
      expect(log.external_id).toBe(session.id)
      expect(log.payment_request_id).toBe(session.id)
      expect(log.status).toBe('PAID')
      expect(Number(log.amount)).toBe(50_000)
      expect(log.currency).toBe('IDR')
      expect(log.payment_method).toBe('BCA')
      expect(log.paid_at).not.toBeNull()
      expect(log.metadata_app).toBe('halobestie_v2')
      expect(log.http_status).toBe(200)
      expect(log.processing_result).toBe('confirmed')
      expect(log.processing_error).toBeNull()
      expect(log.processed_at).not.toBeNull()
      // raw_body is verbatim — unknown future fields would land here
      expect(log.raw_body.metadata.app).toBe('halobestie_v2')
    })

    it('401 invalid token still logs a row with callback_token_valid=false', async () => {
      const res = await fireWebhook(
        app,
        { id: 'inv_log_401', external_id: 'whatever', status: 'PAID', amount: 1 },
        'wrong-token-but-same-length-padding',
      )
      expect(res.statusCode).toBe(401)

      const log = await latestLog()
      expect(log.callback_token_valid).toBe(false)
      expect(log.http_status).toBe(401)
      expect(log.processing_result).toBe('rejected_invalid_token')
      // Raw body still captured even though the request was rejected
      expect(log.raw_body.id).toBe('inv_log_401')
    })

    it('redacts x-callback-token in stored headers', async () => {
      await fireWebhook(app, { id: 'inv_redact', external_id: 'x', status: 'PAID', amount: 1 })
      const log = await latestLog()
      expect(log.headers['x-callback-token']).toBe('[REDACTED]')
      // Non-secret headers are kept (e.g. content-type)
      expect(log.headers['content-type']).toMatch(/application\/json/)
    })

    it('amount mismatch (409) logs rejected_amount_mismatch', async () => {
      const session = await requestPayment({
        productType: 'chat_session',
        customerId: customer.id, durationMinutes: 12, amount: 50_000,
      })
      const res = await fireWebhook(app, {
        id: 'inv_log_mismatch', external_id: session.id, status: 'PAID', amount: 999,
      })
      expect(res.statusCode).toBe(409)

      const log = await latestLog()
      expect(log.http_status).toBe(409)
      expect(log.processing_result).toBe('rejected_amount_mismatch')
      expect(Number(log.amount)).toBe(999)
    })

    it('unknown payment_request still logs ignored_unknown_payment_request', async () => {
      await fireWebhook(app, {
        id: 'inv_log_orphan',
        external_id: '00000000-0000-0000-0000-000000000000',
        status: 'PAID',
        amount: 50_000,
      })
      const log = await latestLog()
      expect(log.processing_result).toBe('ignored_unknown_payment_request')
      expect(log.payment_request_id).toBe('00000000-0000-0000-0000-000000000000')
    })

    it('missing external_id logs ignored_no_external_id with payment_request_id NULL', async () => {
      await fireWebhook(app, { id: 'evt_nox', status: 'SOMETHING' })
      const log = await latestLog()
      expect(log.processing_result).toBe('ignored_no_external_id')
      expect(log.external_id).toBeNull()
      expect(log.payment_request_id).toBeNull()
    })

    it('non-UUID external_id ACKs 200 and logs ignored_non_uuid_external_id', async () => {
      const res = await fireWebhook(app, {
        id: 'inv_log_legacy',
        external_id: 'legacy-old-app-id-42',
        status: 'PAID',
        amount: 1,
      })
      expect(res.statusCode).toBe(200)
      expect(res.json().ignored).toBe('non_uuid_external_id')

      const log = await latestLog()
      expect(log.external_id).toBe('legacy-old-app-id-42')
      expect(log.payment_request_id).toBeNull()
      expect(log.processing_result).toBe('ignored_non_uuid_external_id')
      expect(log.http_status).toBe(200)
    })

    it('logs raw_body verbatim including unknown fields', async () => {
      const session = await requestPayment({
        productType: 'chat_session',
        customerId: customer.id, durationMinutes: 12, amount: 50_000,
      })
      await fireWebhook(app, {
        id: 'inv_log_extra',
        external_id: session.id,
        status: 'PAID',
        amount: 50_000,
        future_field_we_dont_know_yet: { nested: ['anything', 42] },
        metadata: { app: 'halobestie_v2', extra: 'preserved' },
      })
      const log = await latestLog()
      expect(log.raw_body.future_field_we_dont_know_yet.nested).toEqual(['anything', 42])
      expect(log.raw_body.metadata.extra).toBe('preserved')
      expect(log.metadata_app).toBe('halobestie_v2')
    })

    it('survives processing exceptions: logs processing_error + http_status=500', async () => {
      // Force an exception by stubbing getPayment to throw. The survival
      // contract is that even when the handler errors, the forensic row is
      // intact and stamped — Xendit will retry on its own, but we have the
      // record either way.
      const paymentSvc = await import('../../src/services/payment.service.js')
      const orig = paymentSvc.getPayment
      const stub = vi.spyOn(paymentSvc, 'getPayment').mockImplementation(async () => {
        throw new Error('synthetic_db_outage')
      })
      try {
        const res = await fireWebhook(app, {
          id: 'inv_boom',
          external_id: '11111111-1111-1111-1111-111111111111',
          status: 'PAID',
          amount: 50_000,
        })
        expect(res.statusCode).toBe(500)

        const log = await latestLog()
        expect(log.http_status).toBe(500)
        expect(log.processing_result).toBe('error')
        expect(log.processing_error).toBe('synthetic_db_outage')
        expect(log.xendit_event_id).toBe('inv_boom')
        // Raw body is still there even though processing blew up
        expect(log.raw_body.id).toBe('inv_boom')
      } finally {
        stub.mockRestore()
        void orig
      }
    })
  })
})
