"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var typeorm_1 = require("typeorm");
var bcrypt = require("bcrypt");
var user_entity_1 = require("../../users/entities/user.entity");
var category_entity_1 = require("../../categories/entities/category.entity");
var channel_entity_1 = require("../../channels/entities/channel.entity");
var movie_entity_1 = require("../../movies/entities/movie.entity");
var series_entity_1 = require("../../series/entities/series.entity");
var season_entity_1 = require("../../series/entities/season.entity");
var episode_entity_1 = require("../../series/entities/episode.entity");
var profile_entity_1 = require("../../profiles/entities/profile.entity");
var favorite_entity_1 = require("../../favorites/entities/favorite.entity");
var history_entity_1 = require("../../history/entities/history.entity");
var dataSource = new typeorm_1.DataSource({
    type: 'postgres',
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '5432', 10),
    username: process.env.DB_USERNAME || 'postgres',
    password: process.env.DB_PASSWORD || 'postgres',
    database: process.env.DB_NAME || 'rtvgo',
    entities: [user_entity_1.User, category_entity_1.Category, channel_entity_1.Channel, movie_entity_1.Movie, series_entity_1.Series, season_entity_1.Season, episode_entity_1.Episode, profile_entity_1.Profile, favorite_entity_1.Favorite, history_entity_1.History],
    synchronize: true,
    logging: true,
});
function seed() {
    return __awaiter(this, void 0, void 0, function () {
        var userRepo, categoryRepo, channelRepo, movieRepo, seriesRepo, seasonRepo, episodeRepo, existingAdmin, passwordHash, admin, categoriesData, categories, _i, categoriesData_1, catData, existing, category, saved, channelsData, _a, channelsData_1, chData, existing, category, channel, moviesData, _b, moviesData_1, movieData, existing, movieCategories, movie, seriesData, _c, seriesData_1, sd, existing, seriesCategories, series, savedSeries, _d, _e, seasonData, season, savedSeason, _f, _g, epData, episode, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3;
        return __generator(this, function (_4) {
            switch (_4.label) {
                case 0:
                    console.log('🌱 Starting database seed...');
                    return [4 /*yield*/, dataSource.initialize()];
                case 1:
                    _4.sent();
                    console.log('✅ Database connection established');
                    userRepo = dataSource.getRepository(user_entity_1.User);
                    categoryRepo = dataSource.getRepository(category_entity_1.Category);
                    channelRepo = dataSource.getRepository(channel_entity_1.Channel);
                    movieRepo = dataSource.getRepository(movie_entity_1.Movie);
                    seriesRepo = dataSource.getRepository(series_entity_1.Series);
                    seasonRepo = dataSource.getRepository(season_entity_1.Season);
                    episodeRepo = dataSource.getRepository(episode_entity_1.Episode);
                    // ── Admin User ───────────────────────────────────────────────────────────
                    console.log('\n👤 Creating admin user...');
                    return [4 /*yield*/, userRepo.findOne({ where: { email: 'admin@rtvgo.com' } })];
                case 2:
                    existingAdmin = _4.sent();
                    if (!!existingAdmin) return [3 /*break*/, 5];
                    return [4 /*yield*/, bcrypt.hash('admin123456', 12)];
                case 3:
                    passwordHash = _4.sent();
                    admin = userRepo.create({
                        email: 'admin@rtvgo.com',
                        username: 'admin',
                        passwordHash: passwordHash,
                        role: 'ADMIN',
                        status: 'ACTIVE',
                    });
                    return [4 /*yield*/, userRepo.save(admin)];
                case 4:
                    _4.sent();
                    console.log('  ✅ Admin user created (admin@rtvgo.com / admin123456)');
                    return [3 /*break*/, 6];
                case 5:
                    console.log('  ⏭️  Admin user already exists');
                    _4.label = 6;
                case 6:
                    // ── Categories ───────────────────────────────────────────────────────────
                    console.log('\n📂 Creating categories...');
                    categoriesData = [
                        { name: 'Deportes', slug: 'deportes', icon: '⚽', type: 'TV', order: 1 },
                        { name: 'Noticias', slug: 'noticias', icon: '📰', type: 'TV', order: 2 },
                        { name: 'Infantiles', slug: 'infantiles', icon: '🧸', type: 'ALL', order: 3 },
                        { name: 'Entretenimiento', slug: 'entretenimiento', icon: '🎭', type: 'TV', order: 4 },
                        { name: 'Música', slug: 'musica', icon: '🎵', type: 'TV', order: 5 },
                        { name: 'Documentales', slug: 'documentales', icon: '🎬', type: 'ALL', order: 6 },
                        { name: 'Acción', slug: 'accion', icon: '💥', type: 'MOVIE', order: 7 },
                        { name: 'Comedia', slug: 'comedia', icon: '😂', type: 'ALL', order: 8 },
                        { name: 'Terror', slug: 'terror', icon: '👻', type: 'MOVIE', order: 9 },
                        { name: 'Drama', slug: 'drama', icon: '🎭', type: 'ALL', order: 10 },
                        { name: 'Ciencia Ficción', slug: 'ciencia-ficcion', icon: '🚀', type: 'ALL', order: 11 },
                    ];
                    categories = {};
                    _i = 0, categoriesData_1 = categoriesData;
                    _4.label = 7;
                case 7:
                    if (!(_i < categoriesData_1.length)) return [3 /*break*/, 12];
                    catData = categoriesData_1[_i];
                    return [4 /*yield*/, categoryRepo.findOne({ where: { slug: catData.slug } })];
                case 8:
                    existing = _4.sent();
                    if (!!existing) return [3 /*break*/, 10];
                    category = categoryRepo.create(catData);
                    return [4 /*yield*/, categoryRepo.save(category)];
                case 9:
                    saved = _4.sent();
                    categories[catData.slug] = saved;
                    console.log("  \u2705 Category \"".concat(catData.name, "\" created"));
                    return [3 /*break*/, 11];
                case 10:
                    categories[catData.slug] = existing;
                    console.log("  \u23ED\uFE0F  Category \"".concat(catData.name, "\" already exists"));
                    _4.label = 11;
                case 11:
                    _i++;
                    return [3 /*break*/, 7];
                case 12:
                    // ── Channels ─────────────────────────────────────────────────────────────
                    console.log('\n📺 Creating sample channels...');
                    channelsData = [
                        {
                            name: 'ESPN Deportes',
                            streamUrl: 'https://stream.example.com/live/espn-deportes.m3u8',
                            logoUrl: 'https://upload.wikimedia.org/wikipedia/commons/2/2f/ESPN_wordmark.svg',
                            categorySlug: 'deportes',
                            order: 1,
                        },
                        {
                            name: 'CNN en Español',
                            streamUrl: 'https://stream.example.com/live/cnn-espanol.m3u8',
                            logoUrl: 'https://upload.wikimedia.org/wikipedia/commons/b/b1/CNN.svg',
                            categorySlug: 'noticias',
                            order: 1,
                        },
                        {
                            name: 'Cartoon Network',
                            streamUrl: 'https://stream.example.com/live/cartoon-network.m3u8',
                            logoUrl: 'https://upload.wikimedia.org/wikipedia/commons/8/80/Cartoon_Network_2010_logo.svg',
                            categorySlug: 'infantiles',
                            order: 1,
                        },
                        {
                            name: 'Discovery Channel',
                            streamUrl: 'https://stream.example.com/live/discovery.m3u8',
                            logoUrl: 'https://upload.wikimedia.org/wikipedia/commons/a/a0/Discovery_Channel_logo.svg',
                            categorySlug: 'documentales',
                            order: 1,
                        },
                        {
                            name: 'MTV Latinoamérica',
                            streamUrl: 'https://stream.example.com/live/mtv-latam.m3u8',
                            logoUrl: 'https://upload.wikimedia.org/wikipedia/commons/6/68/MTV_Logo.svg',
                            categorySlug: 'musica',
                            order: 1,
                        },
                    ];
                    _a = 0, channelsData_1 = channelsData;
                    _4.label = 13;
                case 13:
                    if (!(_a < channelsData_1.length)) return [3 /*break*/, 18];
                    chData = channelsData_1[_a];
                    return [4 /*yield*/, channelRepo.findOne({ where: { name: chData.name } })];
                case 14:
                    existing = _4.sent();
                    if (!!existing) return [3 /*break*/, 16];
                    category = categories[chData.categorySlug];
                    channel = channelRepo.create({
                        name: chData.name,
                        streamUrl: chData.streamUrl,
                        logoUrl: chData.logoUrl,
                        categoryId: category.id,
                        order: chData.order,
                        isActive: true,
                    });
                    return [4 /*yield*/, channelRepo.save(channel)];
                case 15:
                    _4.sent();
                    console.log("  \u2705 Channel \"".concat(chData.name, "\" created"));
                    return [3 /*break*/, 17];
                case 16:
                    console.log("  \u23ED\uFE0F  Channel \"".concat(chData.name, "\" already exists"));
                    _4.label = 17;
                case 17:
                    _a++;
                    return [3 /*break*/, 13];
                case 18:
                    // ── Movies ───────────────────────────────────────────────────────────────
                    console.log('\n🎬 Creating sample movies...');
                    moviesData = [
                        {
                            title: 'El Secreto de la Montaña',
                            synopsis: 'Un grupo de escaladores descubre un misterio ancestral oculto en las cumbres de los Andes.',
                            streamUrl: 'https://stream.example.com/movies/secreto-montana.m3u8',
                            posterUrl: 'https://picsum.photos/seed/movie1/300/450',
                            backdropUrl: 'https://picsum.photos/seed/movie1bg/1280/720',
                            durationMin: 128,
                            year: 2024,
                            rating: 7.8,
                            categorySlugs: ['accion', 'drama'],
                        },
                        {
                            title: 'Código Nocturno',
                            synopsis: 'Un hacker descubre una conspiración global que amenaza con destruir la infraestructura digital del mundo.',
                            streamUrl: 'https://stream.example.com/movies/codigo-nocturno.m3u8',
                            posterUrl: 'https://picsum.photos/seed/movie2/300/450',
                            backdropUrl: 'https://picsum.photos/seed/movie2bg/1280/720',
                            durationMin: 142,
                            year: 2023,
                            rating: 8.2,
                            categorySlugs: ['ciencia-ficcion', 'accion'],
                        },
                        {
                            title: 'Risas al Amanecer',
                            synopsis: 'Una comedia sobre una familia disfuncional que intenta organizar la boda perfecta.',
                            streamUrl: 'https://stream.example.com/movies/risas-amanecer.m3u8',
                            posterUrl: 'https://picsum.photos/seed/movie3/300/450',
                            backdropUrl: 'https://picsum.photos/seed/movie3bg/1280/720',
                            durationMin: 95,
                            year: 2024,
                            rating: 6.5,
                            categorySlugs: ['comedia'],
                        },
                        {
                            title: 'La Sombra del Bosque',
                            synopsis: 'Una pareja se muda a una cabaña aislada sin saber que algo habita en la oscuridad del bosque.',
                            streamUrl: 'https://stream.example.com/movies/sombra-bosque.m3u8',
                            posterUrl: 'https://picsum.photos/seed/movie4/300/450',
                            backdropUrl: 'https://picsum.photos/seed/movie4bg/1280/720',
                            durationMin: 110,
                            year: 2023,
                            rating: 7.1,
                            categorySlugs: ['terror'],
                        },
                        {
                            title: 'Horizontes Perdidos',
                            synopsis: 'Un documental épico que explora los rincones más remotos de la Tierra y sus civilizaciones olvidadas.',
                            streamUrl: 'https://stream.example.com/movies/horizontes-perdidos.m3u8',
                            posterUrl: 'https://picsum.photos/seed/movie5/300/450',
                            backdropUrl: 'https://picsum.photos/seed/movie5bg/1280/720',
                            durationMin: 156,
                            year: 2024,
                            rating: 9.0,
                            categorySlugs: ['documentales'],
                        },
                    ];
                    _b = 0, moviesData_1 = moviesData;
                    _4.label = 19;
                case 19:
                    if (!(_b < moviesData_1.length)) return [3 /*break*/, 24];
                    movieData = moviesData_1[_b];
                    return [4 /*yield*/, movieRepo.findOne({ where: { title: movieData.title } })];
                case 20:
                    existing = _4.sent();
                    if (!!existing) return [3 /*break*/, 22];
                    movieCategories = movieData.categorySlugs
                        .map(function (slug) { return categories[slug]; })
                        .filter(Boolean);
                    movie = movieRepo.create({
                        title: movieData.title,
                        synopsis: movieData.synopsis,
                        streamUrl: movieData.streamUrl,
                        posterUrl: movieData.posterUrl,
                        backdropUrl: movieData.backdropUrl,
                        durationMin: movieData.durationMin,
                        year: movieData.year,
                        rating: movieData.rating,
                        isActive: true,
                        categories: movieCategories,
                    });
                    return [4 /*yield*/, movieRepo.save(movie)];
                case 21:
                    _4.sent();
                    console.log("  \u2705 Movie \"".concat(movieData.title, "\" created"));
                    return [3 /*break*/, 23];
                case 22:
                    console.log("  \u23ED\uFE0F  Movie \"".concat(movieData.title, "\" already exists"));
                    _4.label = 23;
                case 23:
                    _b++;
                    return [3 /*break*/, 19];
                case 24:
                    // ── Series ───────────────────────────────────────────────────────────────
                    console.log('\n📺 Creating sample series...');
                    seriesData = [
                        {
                            title: 'Circuito Cerrado',
                            synopsis: 'Un detective investiga una serie de crímenes conectados a un sistema de vigilancia secreto en una gran ciudad.',
                            posterUrl: 'https://picsum.photos/seed/series1/300/450',
                            backdropUrl: 'https://picsum.photos/seed/series1bg/1280/720',
                            year: 2023,
                            rating: 8.5,
                            categorySlugs: ['drama', 'ciencia-ficcion'],
                            seasons: [
                                {
                                    number: 1,
                                    title: 'La Red',
                                    episodes: [
                                        { number: 1, title: 'Piloto', streamUrl: 'https://stream.example.com/series/cc/s01e01.m3u8', durationMin: 52 },
                                        { number: 2, title: 'Conexiones', streamUrl: 'https://stream.example.com/series/cc/s01e02.m3u8', durationMin: 48 },
                                        { number: 3, title: 'El Infiltrado', streamUrl: 'https://stream.example.com/series/cc/s01e03.m3u8', durationMin: 55 },
                                        { number: 4, title: 'Punto Ciego', streamUrl: 'https://stream.example.com/series/cc/s01e04.m3u8', durationMin: 50 },
                                        { number: 5, title: 'La Verdad', streamUrl: 'https://stream.example.com/series/cc/s01e05.m3u8', durationMin: 58 },
                                    ],
                                },
                                {
                                    number: 2,
                                    title: 'El Protocolo',
                                    episodes: [
                                        { number: 1, title: 'Nuevo Orden', streamUrl: 'https://stream.example.com/series/cc/s02e01.m3u8', durationMin: 54 },
                                        { number: 2, title: 'Doble Filo', streamUrl: 'https://stream.example.com/series/cc/s02e02.m3u8', durationMin: 51 },
                                        { number: 3, title: 'Colapso', streamUrl: 'https://stream.example.com/series/cc/s02e03.m3u8', durationMin: 60 },
                                    ],
                                },
                            ],
                        },
                        {
                            title: 'Tierra Salvaje',
                            synopsis: 'Un grupo de biólogos se adentra en territorios inexplorados para documentar especies en peligro de extinción.',
                            posterUrl: 'https://picsum.photos/seed/series2/300/450',
                            backdropUrl: 'https://picsum.photos/seed/series2bg/1280/720',
                            year: 2024,
                            rating: 9.1,
                            categorySlugs: ['documentales'],
                            seasons: [
                                {
                                    number: 1,
                                    title: 'Amazonas',
                                    episodes: [
                                        { number: 1, title: 'El Corazón Verde', streamUrl: 'https://stream.example.com/series/ts/s01e01.m3u8', durationMin: 45 },
                                        { number: 2, title: 'Ríos de Vida', streamUrl: 'https://stream.example.com/series/ts/s01e02.m3u8', durationMin: 47 },
                                        { number: 3, title: 'Depredadores Nocturnos', streamUrl: 'https://stream.example.com/series/ts/s01e03.m3u8', durationMin: 44 },
                                        { number: 4, title: 'Los Guardianes', streamUrl: 'https://stream.example.com/series/ts/s01e04.m3u8', durationMin: 50 },
                                    ],
                                },
                            ],
                        },
                    ];
                    _c = 0, seriesData_1 = seriesData;
                    _4.label = 25;
                case 25:
                    if (!(_c < seriesData_1.length)) return [3 /*break*/, 37];
                    sd = seriesData_1[_c];
                    return [4 /*yield*/, seriesRepo.findOne({ where: { title: sd.title } })];
                case 26:
                    existing = _4.sent();
                    if (!!existing) return [3 /*break*/, 35];
                    seriesCategories = sd.categorySlugs
                        .map(function (slug) { return categories[slug]; })
                        .filter(Boolean);
                    series = seriesRepo.create({
                        title: sd.title,
                        synopsis: sd.synopsis,
                        posterUrl: sd.posterUrl,
                        backdropUrl: sd.backdropUrl,
                        year: sd.year,
                        rating: sd.rating,
                        isActive: true,
                        categories: seriesCategories,
                    });
                    return [4 /*yield*/, seriesRepo.save(series)];
                case 27:
                    savedSeries = _4.sent();
                    _d = 0, _e = sd.seasons;
                    _4.label = 28;
                case 28:
                    if (!(_d < _e.length)) return [3 /*break*/, 34];
                    seasonData = _e[_d];
                    season = seasonRepo.create({
                        seriesId: savedSeries.id,
                        number: seasonData.number,
                        title: seasonData.title,
                    });
                    return [4 /*yield*/, seasonRepo.save(season)];
                case 29:
                    savedSeason = _4.sent();
                    _f = 0, _g = seasonData.episodes;
                    _4.label = 30;
                case 30:
                    if (!(_f < _g.length)) return [3 /*break*/, 33];
                    epData = _g[_f];
                    episode = episodeRepo.create({
                        seasonId: savedSeason.id,
                        number: epData.number,
                        title: epData.title,
                        streamUrl: epData.streamUrl,
                        durationMin: epData.durationMin,
                    });
                    return [4 /*yield*/, episodeRepo.save(episode)];
                case 31:
                    _4.sent();
                    _4.label = 32;
                case 32:
                    _f++;
                    return [3 /*break*/, 30];
                case 33:
                    _d++;
                    return [3 /*break*/, 28];
                case 34:
                    console.log("  \u2705 Series \"".concat(sd.title, "\" created with ").concat(sd.seasons.length, " season(s)"));
                    return [3 /*break*/, 36];
                case 35:
                    console.log("  \u23ED\uFE0F  Series \"".concat(sd.title, "\" already exists"));
                    _4.label = 36;
                case 36:
                    _c++;
                    return [3 /*break*/, 25];
                case 37:
                    // ── Done ─────────────────────────────────────────────────────────────────
                    console.log('\n✨ Seed completed successfully!');
                    console.log('\n📋 Summary:');
                    _j = (_h = console).log;
                    _k = "   Users:      ".concat;
                    return [4 /*yield*/, userRepo.count()];
                case 38:
                    _j.apply(_h, [_k.apply("   Users:      ", [_4.sent()])]);
                    _m = (_l = console).log;
                    _o = "   Categories: ".concat;
                    return [4 /*yield*/, categoryRepo.count()];
                case 39:
                    _m.apply(_l, [_o.apply("   Categories: ", [_4.sent()])]);
                    _q = (_p = console).log;
                    _r = "   Channels:   ".concat;
                    return [4 /*yield*/, channelRepo.count()];
                case 40:
                    _q.apply(_p, [_r.apply("   Channels:   ", [_4.sent()])]);
                    _t = (_s = console).log;
                    _u = "   Movies:     ".concat;
                    return [4 /*yield*/, movieRepo.count()];
                case 41:
                    _t.apply(_s, [_u.apply("   Movies:     ", [_4.sent()])]);
                    _w = (_v = console).log;
                    _x = "   Series:     ".concat;
                    return [4 /*yield*/, seriesRepo.count()];
                case 42:
                    _w.apply(_v, [_x.apply("   Series:     ", [_4.sent()])]);
                    _z = (_y = console).log;
                    _0 = "   Seasons:    ".concat;
                    return [4 /*yield*/, seasonRepo.count()];
                case 43:
                    _z.apply(_y, [_0.apply("   Seasons:    ", [_4.sent()])]);
                    _2 = (_1 = console).log;
                    _3 = "   Episodes:   ".concat;
                    return [4 /*yield*/, episodeRepo.count()];
                case 44:
                    _2.apply(_1, [_3.apply("   Episodes:   ", [_4.sent()])]);
                    return [4 /*yield*/, dataSource.destroy()];
                case 45:
                    _4.sent();
                    console.log('\n🔌 Database connection closed');
                    return [2 /*return*/];
            }
        });
    });
}
seed().catch(function (error) {
    console.error('❌ Seed failed:', error);
    process.exit(1);
});
