import { Router, Request, Response } from 'express';
import { PlatformAccountService } from '../../services/platform/PlatformAccountService';
import { requirePermission } from '../../core/guards/rbac.guard';
import { logger } from '../../utils/logger';

const router = Router();

router.get('/list', requirePermission('platform:read'), async (req: Request, res: Response) => {
  try {
    const tenantId = req.user?.tenantId;
    if (!tenantId) {
      return res.status(401).json({ error: 'Unauthorized' });
    }

    const { platform, status, shopId } = req.query;
    const accounts = await PlatformAccountService.list(tenantId, {
      platform: platform as string,
      status: status as string,
      shopId: shopId as string,
    });

    res.json({ success: true, data: accounts });
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    logger.error(`[PlatformAuth] List error: ${errorMessage}`);
    res.status(500).json({ error: errorMessage });
  }
});

router.get('/stats/overview', requirePermission('platform:read'), async (req: Request, res: Response) => {
  try {
    const tenantId = req.user?.tenantId;
    if (!tenantId) {
      return res.status(401).json({ error: 'Unauthorized' });
    }

    const stats = await PlatformAccountService.getStats(tenantId);

    res.json({ success: true, data: stats });
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    logger.error(`[PlatformAuth] Stats error: ${errorMessage}`);
    res.status(500).json({ error: errorMessage });
  }
});

router.get('/:id', requirePermission('platform:read'), async (req: Request, res: Response) => {
  try {
    const id = String(req.params.id);
    const account = await PlatformAccountService.getById(id);

    if (!account) {
      return res.status(404).json({ error: 'Account not found' });
    }

    if (account.tenantId !== req.user?.tenantId) {
      return res.status(403).json({ error: 'Forbidden' });
    }

    res.json({ success: true, data: account });
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    logger.error(`[PlatformAuth] Get error: ${errorMessage}`);
    res.status(500).json({ error: errorMessage });
  }
});

router.post('/connect', requirePermission('platform:write'), async (req: Request, res: Response) => {
  try {
    const tenantId = req.user?.tenantId;
    if (!tenantId) {
      return res.status(401).json({ error: 'Unauthorized' });
    }

    const { platform, accountName, accountId, shopId, config } = req.body;

    if (!platform || !accountName || !accountId) {
      return res.status(400).json({ error: 'Missing required fields' });
    }

    const account = await PlatformAccountService.create(tenantId, {
      platform,
      accountName,
      accountId,
      shopId,
      config,
    });

    const authUrl = PlatformAccountService.generateOAuthUrl(account.id, platform);

    res.json({ 
      success: true, 
      data: { 
        account,
        authUrl,
      }
    });
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    logger.error(`[PlatformAuth] Connect error: ${errorMessage}`);
    res.status(500).json({ error: errorMessage });
  }
});

router.post('/callback/:platform', async (req: Request, res: Response) => {
  try {
    const platform = String(req.params.platform);
    const code = String(req.query.code || '');
    const state = String(req.query.state || '');

    if (!code || !state) {
      return res.status(400).json({ error: 'Missing authorization code or state' });
    }

    const result = await PlatformAccountService.handleOAuthCallback(platform, code, state);

    const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:8000';
    
    if (result.success) {
      res.redirect(`${frontendUrl}/dashboard/settings/platform-auth?status=connected&platform=${platform}`);
    } else {
      res.redirect(`${frontendUrl}/dashboard/settings/platform-auth?status=error&message=${encodeURIComponent(result.error || 'Unknown error')}`);
    }
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    logger.error(`[PlatformAuth] Callback error: ${errorMessage}`);
    const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:8000';
    res.redirect(`${frontendUrl}/dashboard/settings/platform-auth?status=error&message=${encodeURIComponent(errorMessage)}`);
  }
});

router.post('/refresh/:id', requirePermission('platform:write'), async (req: Request, res: Response) => {
  try {
    const id = String(req.params.id);
    const account = await PlatformAccountService.getById(id);

    if (!account) {
      return res.status(404).json({ error: 'Account not found' });
    }

    if (account.tenantId !== req.user?.tenantId) {
      return res.status(403).json({ error: 'Forbidden' });
    }

    const refreshed = await PlatformAccountService.refreshToken(id);

    res.json({ success: true, data: refreshed });
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    logger.error(`[PlatformAuth] Refresh error: ${errorMessage}`);
    res.status(500).json({ error: errorMessage });
  }
});

router.post('/disconnect/:id', requirePermission('platform:write'), async (req: Request, res: Response) => {
  try {
    const id = String(req.params.id);
    const account = await PlatformAccountService.getById(id);

    if (!account) {
      return res.status(404).json({ error: 'Account not found' });
    }

    if (account.tenantId !== req.user?.tenantId) {
      return res.status(403).json({ error: 'Forbidden' });
    }

    await PlatformAccountService.disconnect(id);

    res.json({ success: true });
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    logger.error(`[PlatformAuth] Disconnect error: ${errorMessage}`);
    res.status(500).json({ error: errorMessage });
  }
});

router.delete('/:id', requirePermission('platform:write'), async (req: Request, res: Response) => {
  try {
    const id = String(req.params.id);
    const account = await PlatformAccountService.getById(id);

    if (!account) {
      return res.status(404).json({ error: 'Account not found' });
    }

    if (account.tenantId !== req.user?.tenantId) {
      return res.status(403).json({ error: 'Forbidden' });
    }

    await PlatformAccountService.delete(id);

    res.json({ success: true });
  } catch (error: unknown) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    logger.error(`[PlatformAuth] Delete error: ${errorMessage}`);
    res.status(500).json({ error: errorMessage });
  }
});

export default router;
