CREATE TABLE IF NOT EXISTS languages
(
    id   SERIAL PRIMARY KEY,
    code VARCHAR(12)  NOT NULL UNIQUE,
    name VARCHAR(100) NOT NULL
);

INSERT INTO languages (code, name)
VALUES ('en-US', 'English'),
       ('es', 'Spanish'),
       ('ja-JP', 'Japanese'),
       ('pt-BR', 'Portuguese (Brazil)')
ON CONFLICT DO NOTHING;

ALTER TABLE manga_chapters
    ADD COLUMN IF NOT EXISTS language_id BIGINT REFERENCES languages (id);

UPDATE manga_chapters
SET language = NULL;

UPDATE manga_chapters mc
SET language_id = (SELECT id FROM languages WHERE code = 'pt-BR')
FROM manga_provider mp
         JOIN providers p ON mp.provider_id = p.id
WHERE mc.manga_provider_id = mp.id
  AND mc.language IS NULL
  AND p.name ILIKE ANY
      (ARRAY ['Manga Livre Blog', 'Pink Rosa Scan', 'Manga Livre.to', 'Manga Livre', 'MangaDex', 'Bato', 'Taimu']);

UPDATE manga_chapters mc
SET language_id = (SELECT id FROM languages WHERE code = 'en-US')
FROM manga_provider mp
         JOIN providers p ON mp.provider_id = p.id
WHERE mc.manga_provider_id = mp.id
  AND mc.language IS NULL
  AND p.name ILIKE ANY
      (ARRAY ['Manual Import']);

ALTER TABLE manga_chapters
    DROP COLUMN IF EXISTS language;