import { PLAN_FEATURES, PLAN_PRICES } from '@rentaldrivego/types'
import { Router } from 'express'
import { parseBody, parseParams } from '../../http/validate'
import { ok, created } from '../../http/respond'
import { isDatabaseUnavailableError } from '../../lib/isDatabaseUnavailable'
import * as service from './site.service'
import {
  slugParamSchema, bookingParamSchema,
  availabilitySchema, validateCodeSchema, bookSchema, paySchema, capturePaypalSchema, contactSchema,
} from './site.schemas'

const router = Router()

router.get('/platform/homepage', async (_req, res, next) => {
  try {
    ok(res, await service.getPlatformHomepage())
  } catch (err) { next(err) }
})

router.get('/platform/pricing', async (_req, res, next) => {
  try {
    ok(res, await service.getPlatformPricing())
  } catch (err) {
    if (isDatabaseUnavailableError(err)) {
      return res.json({ data: { prices: PLAN_PRICES, planFeatures: PLAN_FEATURES } })
    }
    next(err)
  }
})

router.get('/:slug/brand', async (req, res, next) => {
  try {
    const { slug } = parseParams(slugParamSchema, req)
    ok(res, await service.getBrand(slug))
  } catch (err) {
    if (isDatabaseUnavailableError(err)) {
      return res.json({ data: { company: { id: 'demo', slug: req.params.slug, name: 'Demo Company', phone: null }, brand: null } })
    }
    next(err)
  }
})

router.get('/:slug/vehicles', async (req, res, next) => {
  try {
    const { slug } = parseParams(slugParamSchema, req)
    ok(res, await service.getPublicVehicles(slug))
  } catch (err) {
    if (isDatabaseUnavailableError(err)) return res.json({ data: [] })
    next(err)
  }
})

router.get('/:slug/vehicles/:id', async (req, res, next) => {
  try {
    const { slug, id } = parseParams(bookingParamSchema, req)
    ok(res, await service.getVehicleDetail(slug, id))
  } catch (err) {
    if (isDatabaseUnavailableError(err)) {
      return res.status(503).json({ error: 'database_unavailable', message: 'Vehicle details are temporarily unavailable', statusCode: 503 })
    }
    next(err)
  }
})

router.get('/:slug/offers', async (req, res, next) => {
  try {
    const { slug } = parseParams(slugParamSchema, req)
    ok(res, await service.getOffers(slug))
  } catch (err) {
    if (isDatabaseUnavailableError(err)) return res.json({ data: [] })
    next(err)
  }
})

router.get('/:slug/booking-options', async (req, res, next) => {
  try {
    const { slug } = parseParams(slugParamSchema, req)
    ok(res, await service.getBookingOptions(slug))
  } catch (err) {
    if (isDatabaseUnavailableError(err)) return res.json({ data: { insurancePolicies: [], contractSettings: null } })
    next(err)
  }
})

router.post('/:slug/availability', async (req, res, next) => {
  try {
    const { slug }                       = parseParams(slugParamSchema, req)
    const { vehicleId, startDate, endDate } = parseBody(availabilitySchema, req)
    ok(res, await service.checkAvailability(slug, vehicleId, startDate, endDate))
  } catch (err) {
    if (isDatabaseUnavailableError(err)) {
      return res.status(503).json({ error: 'database_unavailable', message: 'Availability checks are temporarily unavailable', statusCode: 503 })
    }
    next(err)
  }
})

router.post('/:slug/book/validate-code', async (req, res, next) => {
  try {
    const { slug }   = parseParams(slugParamSchema, req)
    const { code }   = parseBody(validateCodeSchema, req)
    ok(res, await service.validatePromoCode(slug, code))
  } catch (err) {
    if (isDatabaseUnavailableError(err)) {
      return res.status(503).json({ error: 'database_unavailable', message: 'Promo code validation is temporarily unavailable', statusCode: 503 })
    }
    next(err)
  }
})

router.post('/:slug/book', async (req, res, next) => {
  try {
    const { slug } = parseParams(slugParamSchema, req)
    const body     = parseBody(bookSchema, req)
    const result   = await service.createBooking(slug, body)
    created(res, result)
  } catch (err) {
    if (isDatabaseUnavailableError(err)) {
      return res.status(503).json({ error: 'database_unavailable', message: 'Booking is temporarily unavailable', statusCode: 503 })
    }
    next(err)
  }
})

router.get('/:slug/booking/:id', async (req, res, next) => {
  try {
    const { slug, id } = parseParams(bookingParamSchema, req)
    const accessToken = typeof req.query.token === 'string' ? req.query.token : undefined
    ok(res, await service.getBooking(slug, id, accessToken))
  } catch (err) {
    if (isDatabaseUnavailableError(err)) {
      return res.status(503).json({ error: 'database_unavailable', message: 'Booking details are temporarily unavailable', statusCode: 503 })
    }
    next(err)
  }
})

router.post('/:slug/booking/:id/pay', async (req, res, next) => {
  try {
    const { slug, id } = parseParams(bookingParamSchema, req)
    const body         = parseBody(paySchema, req)
    ok(res, await service.initPayment(slug, id, body))
  } catch (err) {
    if (isDatabaseUnavailableError(err)) {
      return res.status(503).json({ error: 'database_unavailable', message: 'Payment initiation is temporarily unavailable', statusCode: 503 })
    }
    next(err)
  }
})

router.post('/:slug/booking/:id/capture-paypal', async (req, res, next) => {
  try {
    const { slug }           = parseParams(slugParamSchema, req)
    const { paypalOrderId }  = parseBody(capturePaypalSchema, req)
    ok(res, await service.capturePaypal(slug, paypalOrderId))
  } catch (err) { next(err) }
})

router.post('/:slug/contact', async (req, res, next) => {
  try {
    const { slug } = parseParams(slugParamSchema, req)
    const body     = parseBody(contactSchema, req)
    ok(res, await service.handleContact(slug, body))
  } catch (err) { next(err) }
})

export default router
