import { Controller, Get, Post, Req, Res, UnauthorizedException, UseGuards } from '@nestjs/common';
import { OIDCLoginGuard } from '../guards/authentik-auth.guard';
import { Request, Response } from 'express';
import { UsersService } from 'src/identity-and-account/users-management/services/users.service';
import { Access } from 'src/common/decorators/module-access.decorators';

@Controller('auth')
export class AuthController {
    constructor(
        private readonly usersService: UsersService,
    ) { }

    @UseGuards(OIDCLoginGuard)
    @Get('v1/login')
    login() { }

    @Get('callback')
    @UseGuards(OIDCLoginGuard)
    loginCallback(@Req() req: Request, @Res() res: Response) {
        res.redirect(process.env.REDIRECT_URL_DEV!);
    }

    @Get('me')
    async getProfile(
        @Access('email') email: string,
        @Req() req: Request) {
        if (!req.user) {
            throw new UnauthorizedException('Not logged in');
        }
        return this.usersService.findOneByEmail(email);
    }

    @Post('logout')
    logout(
        @Req() request: Request,
        @Res() response: Response,
    ) {
        request.session.destroy(error => {
            if (error) {
                console.error('error during logout: ', error, 'user: ', request.user);
            }

            response.clearCookie('connect.sid', {
                path: '/',
            });
        })
    }
}
