import {
  Controller,
  Get,
  Post,
  Req,
  Res,
  // UnauthorizedException,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Request, Response } from 'express';
import { Session } from 'express-session';
import { SamlAuthGuard } from '../samlAuthGuard';
import { Public } from '../public.decorator';
import { UserService } from '../../user/user.service';
import { JwtService } from '@nestjs/jwt';
import { ApiTags, ApiOperation } from '@nestjs/swagger';

interface User {
  id: string;
  sessionIndex: string; // Add this line
  // Add other properties as needed
}

interface SessionWithUser extends Session {
  user?: User;
  sessionIndex?: string;
}

export interface RequestWithSession extends Request {
  session: SessionWithUser;
  user: User;
}

@ApiTags('auth')
@Controller()
export class AuthController {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
  ) {}

  @Public()
  @Get('login')
  @UseGuards(AuthGuard('saml'))
  @ApiOperation({ summary: 'Initiate SAML Login' })
  login() {}

  @Public()
  @Post('login/callback')
  @UseGuards(SamlAuthGuard)
  @ApiOperation({ summary: 'SAML Login Callback' })
  callback(@Req() req: RequestWithSession, @Res() res: Response) {
    const frontendUrl = process.env.FRONTEND_URL;
    const sessionIndex = req.session.sessionIndex || '';
    req.session[sessionIndex] = req.user; // Store the user data under the sessionIndex key

    try {
      // Redirect to the frontend with the sessionIndex as a query parameter
      res.redirect(`${frontendUrl}?sessionIndex=${sessionIndex}`);
    } catch (error) {
      // Redirect to the frontend with the error message as a query parameter
      const errorMessage =
        error instanceof Error ? error.message : JSON.stringify(error);
      res.redirect(
        `${frontendUrl}?errorMessage=${encodeURIComponent(errorMessage)}`,
      );
    }
  }
  // @Public()
  // @Get('profile')
  // @UseGuards(AuthGuard('session')) // Uncomment this line
  // async profile(@Req() req: RequestWithSession, @Res() res: Response) {
  //   const sessionIndex = req.headers['sessionindex'] as string; // Headers are case-insensitive

  //   // Call the service method to get user data
  //   const email =
  //     await this.userService.getUserDataBySessionIndex(sessionIndex);

  //   if (!email) {
  //     throw new UnauthorizedException(
  //       'Invalid session index or user not found',
  //     );
  //   }

  //   let user = await this.userService.getUserWithCompanyTentInfo(email, false);
  //   if (!user) {
  //     user = await this.userService.getUserWithCompanyTentInfo(email, true);
  //     if (!user) {
  //       throw new UnauthorizedException(
  //         'Invalid session index or user not found',
  //       );
  //     }
  //   }

  //   // Fetch moduleAccess from the database
  //   const moduleAccess = await this.userService.getUserModuleAccess(
  //     user.employeePk,
  //     user.department,
  //   );
  //   // Add moduleAccess to the user object
  //   user.moduleAccess = moduleAccess;

  //   const payload = {
  //     username: user.email,
  //     sub: user.employeePk,
  //     sessionId: sessionIndex, // include session ID
  //     ip: req.ip, // include client's IP address
  //     host: (req as any).hostname, // include client's host
  //   };

  //   const access_token = this.jwtService.sign(payload, { expiresIn: '24h' }); // access token expires in 24 hours
  //   const refresh_token = this.jwtService.sign(payload, { expiresIn: '24h' }); // refresh token expires in 24 hours
  //   user.access_token = access_token;
  //   user.refresh_token = refresh_token;

  //   if (!user) {
  //     throw new UnauthorizedException(
  //       'Invalid session index or user not found',
  //     );
  //   }

  //   return res.json(user);
  // }
}
