import { Controller, Get, Delete, Param, UseGuards, NotFoundException } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { User } from '../../entities/user.entity';
import { BuildService } from '../builds/build.service';

@Controller('api/apps')
export class AppsController {
  constructor(private buildService: BuildService) { }

  @Get()
  @UseGuards(JwtAuthGuard)
  async list(@CurrentUser() user: User) {
    const apps = await this.buildService.getAppsByUser(user.id);
    const isLocal = process.env.NODE_ENV !== 'production' && (!process.env.FRONTEND_URL || process.env.FRONTEND_URL.includes('localhost'));
    const defaultApiUrl = isLocal ? 'http://localhost:4000' : 'https://deployhub-back.workzy.co';
    let apiUrl = (process.env.PUBLIC_BASE_URL || defaultApiUrl).trim();
    if (apiUrl.endsWith('/')) apiUrl = apiUrl.slice(0, -1);
    
    // Auto-correct if frontend URL is mistakenly provided instead of backend URL
    if (apiUrl.includes('deployhub.workzy.co') && !apiUrl.includes('deployhub-back.workzy.co')) {
      apiUrl = 'https://deployhub-back.workzy.co';
    }

    return apps
      .filter((app) => app.builds?.length > 0)
      .map((app) => ({
        id: app.id,
        platform: app.platform,
        appName: app.appName,
        bundleOrPackage: app.bundleOrPackage,
        createdAt: app.createdAt,
        iconUrl: (app.iconData || app.iconFileId)
          ? `${apiUrl}/api/drive/icon/${app.id}`
          : undefined,
        builds: app.builds
          .sort(
            (a, b) =>
              new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
          )
          .map((b) => ({
            id: b.id,
            version: b.version,
            buildNumber: b.buildNumber,
            minOs: b.minOs,
            size: b.size,
            createdAt: b.createdAt,
            shortCode: b.shortCode,
            updateDescription: b.updateDescription ?? undefined,
            udids: b.udids ?? undefined,
            buildType: b.buildType ?? undefined,
            provisioningProfile: b.provisioningProfile ?? undefined,
            isPasswordProtected: b.isPasswordProtected ?? false,
            passwordText: b.passwordText ?? undefined,
          })),
      }));
  }

  @Delete(':id')
  @UseGuards(JwtAuthGuard)
  async deleteApp(@CurrentUser() user: User, @Param('id') appId: string) {
    const deleted = await this.buildService.deleteApp(appId, user.id);
    if (!deleted) throw new NotFoundException('App not found');
    return { success: true };
  }
}
