import { Router, Request, Response } from 'express';
import crypto from 'crypto';
import axios from 'axios';
import { salla } from '../config';
import { getAuthStatus, setTokens, callSallaAPI } from '../services/sallaClient';

const router = Router();
let oauthState: string | null = null;

// OAuth: redirect to Salla authorization
router.get('/auth/login', (_req: Request, res: Response) => {
  oauthState = crypto.randomBytes(16).toString('hex');

  const authUrl =
    `https://accounts.salla.sa/oauth2/auth?` +
    `client_id=${salla.clientId}` +
    `&redirect_uri=${encodeURIComponent(salla.redirectUri)}` +
    `&response_type=code` +
    `&scope=offline_access` +
    `&state=${oauthState}`;

  res.redirect(authUrl);
});

// OAuth: handle callback
router.get('/auth/callback', async (req: Request, res: Response) => {
  const { code, error, state } = req.query;

  if (error) {
    res.status(400).json({ error: 'Authorization denied', details: error });
    return;
  }

  if (!code) {
    res.status(400).json({ error: 'No authorization code received' });
    return;
  }

  if (oauthState && state && state !== oauthState) {
    res.status(400).json({ error: 'Invalid state parameter' });
    return;
  }

  try {
    const response = await axios.post('https://accounts.salla.sa/oauth2/token', {
      client_id: salla.clientId,
      client_secret: salla.clientSecret,
      grant_type: 'authorization_code',
      code,
      redirect_uri: salla.redirectUri,
    });

    setTokens(response.data.access_token, response.data.refresh_token);

    console.log('\n========================================');
    console.log('SALLA CONNECTED SUCCESSFULLY!');
    console.log('========================================');
    console.log('Add these to your .env file:');
    console.log(`SALLA_ACCESS_TOKEN=${response.data.access_token}`);
    console.log(`SALLA_REFRESH_TOKEN=${response.data.refresh_token}`);
    console.log('========================================\n');

    res.send(`
      <html>
        <body style="font-family: Arial; text-align: center; padding: 50px;">
          <h1>Salla Connected!</h1>
          <p>Authorization successful. You can close this window.</p>
          <script>setTimeout(() => window.close(), 3000);</script>
        </body>
      </html>
    `);
  } catch (err: unknown) {
    const axiosErr = err as { response?: { data: unknown }; message: string };
    console.error('Token exchange failed:', axiosErr.response?.data || axiosErr.message);
    res.status(500).json({ error: 'Token exchange failed', details: axiosErr.response?.data });
  }
});

// Auth status
router.get('/auth/status', (_req: Request, res: Response) => {
  res.json(getAuthStatus());
});

// Salla API proxy endpoints
router.get('/api/store', async (_req: Request, res: Response) => {
  try {
    const data = await callSallaAPI('/store/info');
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: (err as Error).message });
  }
});

router.get('/api/orders', async (req: Request, res: Response) => {
  try {
    const { page = 1, per_page = 50, status } = req.query;
    let endpoint = `/orders?page=${page}&per_page=${per_page}`;
    if (status) endpoint += `&status=${status}`;
    const data = await callSallaAPI(endpoint);
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: (err as Error).message });
  }
});

router.get('/api/orders/:id', async (req: Request, res: Response) => {
  try {
    const data = await callSallaAPI(`/orders/${req.params.id}`);
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: (err as Error).message });
  }
});

router.get('/api/products', async (req: Request, res: Response) => {
  try {
    const { page = 1, per_page = 50 } = req.query;
    const data = await callSallaAPI(`/products?page=${page}&per_page=${per_page}`);
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: (err as Error).message });
  }
});

router.get('/api/customers', async (req: Request, res: Response) => {
  try {
    const { page = 1, per_page = 50 } = req.query;
    const data = await callSallaAPI(`/customers?page=${page}&per_page=${per_page}`);
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: (err as Error).message });
  }
});

router.get('/api/analytics/summary', async (_req: Request, res: Response) => {
  try {
    const [orders, products] = await Promise.all([
      callSallaAPI('/orders?per_page=100') as Promise<{ data?: Array<{ amounts?: { total?: { amount?: number; currency?: string } } }>; pagination?: { total?: number } }>,
      callSallaAPI('/products?per_page=100') as Promise<{ data?: unknown[]; pagination?: { total?: number } }>,
    ]);

    const ordersList = orders.data || [];
    const totalRevenue = ordersList.reduce((sum: number, o) => sum + (o.amounts?.total?.amount || 0), 0);
    const avgOrderValue = ordersList.length > 0 ? totalRevenue / ordersList.length : 0;

    res.json({
      orders: { total: orders.pagination?.total || ordersList.length, recent: ordersList.length },
      products: { total: products.pagination?.total || (products.data?.length || 0) },
      revenue: {
        total: totalRevenue,
        average_order: avgOrderValue,
        currency: ordersList[0]?.amounts?.total?.currency || 'SAR',
      },
    });
  } catch (err) {
    res.status(500).json({ error: (err as Error).message });
  }
});

export default router;
