import express from 'express';
import { companySystem } from '../../../../features/company';
import { ChatSystem } from '../../../../features/chat';
import { LogSystem } from '../../../../core/log';
import { getRepository } from 'typeorm';
import { CharacterEntity } from '../../../../entities/character.entity';
import { ChatColors } from '../../../../const/chat-colors';

export async function SetCompanyOwner(req: express.Request, res: express.Response) {
    const by = req.body.by;
    const companyId = Number(req.body.companyId);
    const ownerId = Number(req.body.ownerId);

    const company = companySystem.getCompanyById(companyId);

    if (!company) {
        res.sendStatus(404);
        return;
    }

    if (!ownerId) {
        if (!company.owner_character_id) {
            res.sendStatus(400);
            return;
        }
        ChatSystem.AdminWarn(
            `<Web> ${by} removed ${company.owner?.name} (${company.owner_character_id}) as company ${company.id}'s owner.`,
            'account.admin.setcompany',
        );
        LogSystem.CompanyEvent(
            company,
            'set_company',
            `<Web> ${by} removed ${company.owner?.name} (${company.owner_character_id}) as company ${company.id}'s owner.`,
        );
        company.owner_character_id = null;
        delete company.owner;
        res.sendStatus(200);
        return;
    }

    company.owner_character_id = ownerId;
    company.owner = await getRepository(CharacterEntity).findOne(company.owner_character_id);
    ChatSystem.AdminWarn(`<Web> ${by} set ${company.owner?.name} (${company.owner_character_id}) as company ${company.id} owner.`, 'account.admin.setcompany');
    LogSystem.CompanyEvent(company, 'set_company', `<Web> ${by} set ${company.owner?.name} (${company.owner_character_id}) as company ${company.id} owner.`);

    res.sendStatus(200);
}
