import { describe, expect, it, vi } from 'vitest'
import {
  renderLocalizedEmailHtml,
  resolveNotificationLocale,
  resolveNotificationTemplate,
} from './notificationLocalizationService'

function createDbStub(overrides: Record<string, any> = {}) {
  return {
    employee: {
      findUnique: vi.fn().mockResolvedValue(null),
    },
    renter: {
      findUnique: vi.fn().mockResolvedValue(null),
    },
    brandSettings: {
      findUnique: vi.fn().mockResolvedValue(null),
    },
    billingAccount: {
      findUnique: vi.fn().mockResolvedValue(null),
      findFirst: vi.fn().mockResolvedValue(null),
    },
    notificationTemplate: {
      findFirst: vi.fn().mockResolvedValue(null),
    },
    ...overrides,
  }
}

describe('notificationLocalizationService', () => {
  it('resolves locale in recipient -> workspace -> billing -> default order', async () => {
    const db = createDbStub({
      employee: {
        findUnique: vi.fn().mockResolvedValue({ preferredLanguage: 'ar' }),
      },
      brandSettings: {
        findUnique: vi.fn().mockResolvedValue({ defaultLocale: 'fr' }),
      },
      billingAccount: {
        findUnique: vi.fn().mockResolvedValue(null),
        findFirst: vi.fn().mockResolvedValue({ preferredLanguage: 'en' }),
      },
    })

    const locale = await resolveNotificationLocale({
      companyId: 'company_1',
      employeeId: 'employee_1',
    }, db as any)

    expect(locale).toBe('ar')
  })

  it('falls back to English when a localized template is missing', async () => {
    const db = createDbStub({
      notificationTemplate: {
        findFirst: vi
          .fn()
          .mockImplementation(({ where }: any) => {
            if (where.locale === 'en') {
              return Promise.resolve({
                templateKey: 'booking.confirmed',
                channel: 'EMAIL',
                locale: 'en',
                subject: 'Booking confirmed - {{companyName}}',
                body: 'Hello {{firstName}}',
                requiredVariables: ['companyName', 'firstName'],
                optionalVariables: [],
                version: 1,
              })
            }

            return Promise.resolve(null)
          }),
      },
    })

    const template = await resolveNotificationTemplate({
      templateKey: 'booking.confirmed',
      channel: 'EMAIL',
      locale: 'ar',
      variables: {
        firstName: 'Aya',
        companyName: 'Atlas Cars',
      },
    }, db as any)

    expect(template.locale).toBe('en')
    expect(template.usedFallback).toBe(true)
    expect(template.subject).toBe('Booking confirmed - Atlas Cars')
    expect(template.body).toBe('Hello Aya')
  })

  it('renders Arabic emails with rtl metadata', () => {
    const html = renderLocalizedEmailHtml('مرحبا\n\nتم التأكيد', 'ar')

    expect(html).toContain('<html lang="ar" dir="rtl">')
    expect(html).toContain('text-align:right')
  })
})
