import { Router } from 'express'
import { requireCompanyAuth } from '../../middleware/requireCompanyAuth'
import { requireTenant } from '../../middleware/requireTenant'
import { requireSubscription } from '../../middleware/requireSubscription'
import { requireRole } from '../../middleware/requireRole'
import { requireCompanyPolicy } from '../../middleware/requireCompanyPolicy'
import { parseBody, parseParams } from '../../http/validate'
import { ok, created, noContent } from '../../http/respond'
import { imageUpload, assertImageFile } from '../../http/upload'
import * as service from './company.service'
import {
  normalizeSettingsLocale,
  requireSettingsFeature,
  resolveSettingsEntitlements,
  resolveSettingsMenu,
} from './settingsEntitlements'
import {
  companySchema, brandSchema, contractSettingsSchema,
  insurancePolicySchema, pricingRuleSchema, accountingSettingsSchema,
  subdomainSchema, customDomainSchema, idParamSchema,
} from './company.schemas'

const router = Router()

router.use(requireCompanyAuth, requireTenant, requireSubscription)

router.get('/me', async (req, res, next) => {
  try {
    const company = await service.getCompany(req.companyId)
    ok(res, company)
  } catch (err) { next(err) }
})

router.patch('/me', requireRole('OWNER'), async (req, res, next) => {
  try {
    const body = parseBody(companySchema, req)
    const company = await service.updateCompany(req.companyId, body)
    ok(res, company)
  } catch (err) { next(err) }
})

router.get('/me/brand', async (req, res, next) => {
  try {
    const brand = await service.getBrand(req.companyId)
    ok(res, brand)
  } catch (err) { next(err) }
})

router.patch('/me/brand', requireRole('OWNER'), requireSettingsFeature('settings.branding_basic'), async (req, res, next) => {
  try {
    const body = parseBody(brandSchema, req)
    const brand = await service.updateBrand(req.companyId, body, req.company.name, req.company.slug)
    ok(res, brand)
  } catch (err) { next(err) }
})

router.post('/me/brand/logo', requireRole('OWNER'), requireSettingsFeature('settings.branding_basic'), imageUpload.single('file'), async (req, res, next) => {
  try {
    assertImageFile(req.file, 'logo')
    const brand = await service.uploadLogo(req.companyId, req.company.name, req.company.slug, req.file.buffer)
    ok(res, brand)
  } catch (err) { next(err) }
})

router.post('/me/brand/hero', requireRole('OWNER'), requireSettingsFeature('settings.branding_hero'), imageUpload.single('file'), async (req, res, next) => {
  try {
    assertImageFile(req.file, 'hero image')
    const brand = await service.uploadHeroImage(req.companyId, req.company.name, req.company.slug, req.file.buffer)
    ok(res, brand)
  } catch (err) { next(err) }
})

router.get('/me/settings-menu', async (req, res, next) => {
  try {
    ok(res, await resolveSettingsMenu(req.companyId, normalizeSettingsLocale(req.query.locale as string | undefined)))
  } catch (err) { next(err) }
})

router.get('/me/settings-entitlements', async (req, res, next) => {
  try {
    ok(res, await resolveSettingsEntitlements(req.companyId))
  } catch (err) { next(err) }
})

router.post('/me/brand/subdomain/check', requireRole('OWNER'), async (req, res, next) => {
  try {
    const { subdomain } = parseBody(subdomainSchema, req)
    const result = await service.checkSubdomainAvailability(subdomain, req.companyId)
    ok(res, result)
  } catch (err) { next(err) }
})

router.post('/me/brand/custom-domain', requireRole('OWNER'), async (req, res, next) => {
  try {
    const { customDomain } = parseBody(customDomainSchema, req)
    const brand = await service.setCustomDomain(req.companyId, req.company.name, req.company.slug, customDomain)
    ok(res, brand)
  } catch (err) { next(err) }
})

router.get('/me/brand/custom-domain/status', async (req, res, next) => {
  try {
    const status = await service.getCustomDomainStatus(req.companyId)
    ok(res, status)
  } catch (err) { next(err) }
})

router.delete('/me/brand/custom-domain', requireRole('OWNER'), async (req, res, next) => {
  try {
    const result = await service.removeCustomDomain(req.companyId)
    ok(res, result)
  } catch (err) { next(err) }
})

router.get('/me/contract-settings', async (req, res, next) => {
  try {
    const settings = await service.getContractSettings(req.companyId)
    ok(res, settings)
  } catch (err) { next(err) }
})

router.patch('/me/contract-settings', requireRole('MANAGER'), requireSettingsFeature('settings.rental_policies_basic'), async (req, res, next) => {
  try {
    const body = parseBody(contractSettingsSchema, req)
    const settings = await service.updateContractSettings(req.companyId, body)
    ok(res, settings)
  } catch (err) { next(err) }
})

router.get('/me/insurance-policies', async (req, res, next) => {
  try {
    const policies = await service.getInsurancePolicies(req.companyId)
    ok(res, policies)
  } catch (err) { next(err) }
})

router.post('/me/insurance-policies', requireRole('MANAGER'), requireSettingsFeature('settings.insurance_policies'), async (req, res, next) => {
  try {
    const body = parseBody(insurancePolicySchema, req)
    const policy = await service.createInsurancePolicy(req.companyId, body)
    created(res, policy)
  } catch (err) { next(err) }
})

router.patch('/me/insurance-policies/:id', requireRole('MANAGER'), requireSettingsFeature('settings.insurance_policies'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    const body = parseBody(insurancePolicySchema.partial(), req)
    const policy = await service.updateInsurancePolicy(id, req.companyId, body)
    ok(res, policy)
  } catch (err) { next(err) }
})

router.delete('/me/insurance-policies/:id', requireRole('MANAGER'), requireSettingsFeature('settings.insurance_policies'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    await service.deleteInsurancePolicy(id, req.companyId)
    ok(res, { success: true })
  } catch (err) { next(err) }
})

router.get('/me/pricing-rules', async (req, res, next) => {
  try {
    const rules = await service.getPricingRules(req.companyId)
    ok(res, rules)
  } catch (err) { next(err) }
})

router.post('/me/pricing-rules', requireRole('MANAGER'), requireSettingsFeature('settings.pricing_rules'), async (req, res, next) => {
  try {
    const body = parseBody(pricingRuleSchema, req)
    const rule = await service.createPricingRule(req.companyId, body)
    created(res, rule)
  } catch (err) { next(err) }
})

router.patch('/me/pricing-rules/:id', requireRole('MANAGER'), requireSettingsFeature('settings.pricing_rules'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    const body = parseBody(pricingRuleSchema.partial(), req)
    const rule = await service.updatePricingRule(id, req.companyId, body)
    ok(res, rule)
  } catch (err) { next(err) }
})

router.delete('/me/pricing-rules/:id', requireCompanyPolicy('deletePricingRule'), requireSettingsFeature('settings.pricing_rules'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    await service.deletePricingRule(id, req.companyId)
    ok(res, { success: true })
  } catch (err) { next(err) }
})

router.get('/me/accounting-settings', async (req, res, next) => {
  try {
    const settings = await service.getAccountingSettings(req.companyId)
    ok(res, settings)
  } catch (err) { next(err) }
})

router.patch('/me/accounting-settings', requireCompanyPolicy('updateAccountingSettings'), requireSettingsFeature('settings.accounting_defaults'), async (req, res, next) => {
  try {
    const body = parseBody(accountingSettingsSchema, req)
    const settings = await service.updateAccountingSettings(req.companyId, body)
    ok(res, settings)
  } catch (err) { next(err) }
})

router.get('/me/api-key', requireCompanyPolicy('viewApiKey'), async (req, res, next) => {
  try {
    const company = await service.getApiKey(req.companyId)
    ok(res, company)
  } catch (err) { next(err) }
})

router.post('/me/api-key/regenerate', requireCompanyPolicy('regenerateApiKey'), async (req, res, next) => {
  try {
    const company = await service.regenerateApiKey(req.companyId)
    ok(res, company)
  } catch (err) { next(err) }
})

export default router
