import { MigrationInterface, QueryRunner } from "typeorm";

export class UpdateUserFollowerCount1737711404061 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<void> {
         queryRunner.query(`CREATE OR REPLACE FUNCTION update_user_follower_count() 
                        RETURNS TRIGGER AS $$
                        DECLARE
                            follower_count_diff INT;
                            following_count_diff INT;
                        BEGIN
                            follower_count_diff := NEW.follower_count - OLD.follower_count;
                            following_count_diff := NEW.following_count - OLD.following_count;

                            UPDATE users  
                            SET total_followers = total_followers + follower_count_diff,
                                total_following = total_following + following_count_diff
                            WHERE id = NEW.users;
                            RETURN NEW;

                        END;
                        $$ LANGUAGE plpgsql;

                        CREATE TRIGGER update_user_follower_count
                        AFTER UPDATE ON social_medias
                        FOR EACH ROW
                        EXECUTE FUNCTION update_user_follower_count();`);
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
    }

}
