import { Controller, Get, Req, Res } from '@nestjs/common'
import { Request, Response } from 'express'
import { QuickBooksService } from '@services/quickbooks.service'

@Controller('quickbooks')
export class QuickBooksController {
	constructor(private readonly quickBooksService: QuickBooksService) {}

	@Get('oauth/callback')
	async get(@Req() req: Request, @Res() res: Response) {
		const authCode = req.query.code
		const state = req.query.state

		if (!authCode) return res.status(400).send('Authorization failed.')

		res.send('Authorization successful! Check your terminal for the code.')

		await this.quickBooksService.getAccessToken({ type: 'authCode', code: authCode })
	}

	@Get('oauth/init')
	async init() {
		const url = this.quickBooksService.oAuth()
		return `<a href="${url}">Connect to QuickBooks</a>`
	}

	@Get('oauth/refresh')
	async refresh() {
		await this.quickBooksService.getAccessToken({ type: 'refresh' })
		return true
	}
}
