import { Router } from "express";
import { UserServices } from "../services/user.mjs";
import { normalizeError } from "../common/util.mjs";
import config from 'config';

export function userRouter(userServices: UserServices) {
    const router = Router();

    router.get('/user/:userId', async (req, res) => {
        const user = userServices.get(req.params.userId);

        if (user) {
            res.status(200).json(user);
        } else {
            res.status(400).json({ error: 'user not exist!' });
        }
    });

    // 注册新用户
    router.post('/signup', async (req, res) => {
        const { username, password } = req.body;

        try {
            const { id } = await userServices.signup(username, password);

            res.status(200).json({ id });
        } catch (error) {
            console.log('error', error);
            res.status(400).json({ error: normalizeError(error) });
        }
    });

    // 用户登录，返回 JWT Token
    router.post('/login', async (req, res) => {
        const { username, password } = req.body;

        try {
            const token = await userServices.login(username, password);
            res.status(200).json({ token });
        } catch (error) {
            res.status(400).json({ error: normalizeError(error) });
        }
    });

    router.get('/user/oauth/redirect', async (req, res) => {
        console.log('oauth', req.query);
        const code = req.query.code;
        const clientId = config.get('oauth.github.clientId');
        const clientSecret = config.get('oauth.github.clientSecret');

        try {
            const tokenResponse = await fetch('https://github.com/login/oauth/access_token?' +
                `client_id=${clientId}&` +
                `client_secret=${clientSecret}&` +
                `code=${code}`,
                { method: 'post', headers: { accept: 'application/json' } }
            );
            const json = await tokenResponse.json();
            const accessToken = json.access_token;
            
            console.log('accessToken', accessToken, json);
        
            const userResponse = await fetch('https://api.github.com/user', {
                headers: {
                    accept: 'application/json',
                    Authorization: `token ${accessToken}`
                }
            });
    
            const userJson = await userResponse.json();
    
            const { login } = userJson;
            
            const user = await userServices.getByName(login);
            if (!user) {
                await userServices.signup(login, 'github');
            }
            
            const token = await userServices.login(login, 'github');

            return res.redirect(`/?token=${token}`);
        } catch (error) {
            return res.status(400).json({ error: normalizeError(error) });
        }
    });

    router.get('/users/search/:key(*)', async (req, res) => {
        const users = await userServices.search(req.params.key);
        res.status(200).json(users);
    });

    return router;
}
